This splits indexing into two phases:

* preindex (where only pages, space lua, space styles are indexed)
* index (where everything else is indexed)

The goal is to get to more-or-less operational state quicker this way,
because probably most functionality can already be enabled after the
pre-index phase.
This commit is contained in:
Zef Hemel
2025-12-10 09:48:09 +01:00
parent 5d9caacc30
commit 2efeb93b47
16 changed files with 845 additions and 793 deletions
+48 -20
View File
@@ -202,7 +202,7 @@ export class Client {
this.commandAugmenter = new Augmenter(this.ds, ["aug", "command"]);
// Setup message queue on top of that
this.mq = new DataStoreMQ(this.ds);
this.mq = new DataStoreMQ(this.ds, this.eventHook);
// Instantiate a PlugOS system
this.clientSystem = new ClientSystem(
@@ -330,30 +330,58 @@ export class Client {
async (
name: string,
) => {
// TODO: Optimization opportunity here: dispatch the page:index here directly rather than sending it off to a queue which will refetch the file
console.log("Queueing index for", name);
await this.mq.send("indexQueue", name);
await this.eventHook.dispatchEvent("file:clearindex", name);
await this.mq.send("preIndexQueue", name);
if (await this.clientSystem.hasPreIndexCompleted()) {
// When the client is clean booted (no index yet), we skip indexing on the first pass
// and then schedule it once pre-index has finished for all files
// However, if pre indexing has already completed, then we schedule it immediately
await this.mq.send("indexQueue", name);
}
},
);
this.eventHook.addLocalListener("file:initial", async () => {
const startTime = Date.now();
await this.mq.awaitEmptyQueue("indexQueue");
console.info(
"Initial indexing complete after",
(Date.now() - startTime) / 1000,
"s",
);
await this.clientSystem.markFullSpaceIndexComplete();
await this.clientSystem.reloadState();
});
this.space = new Space(
const space = new Space(
this.eventedSpacePrimitives,
this.eventHook,
);
this.space = space;
let startTime = -1;
this.eventHook.addLocalListener("file:initial", () => {
startTime = Date.now();
});
const emptyQueueHandler = async () => {
if (!await this.clientSystem.hasPreIndexCompleted()) {
// Pre indexing has just finished for the first time
console.info(
"Pre-indexing complete after",
(Date.now() - startTime) / 1000,
"s",
);
// Unsubscribe myself
this.eventHook.removeLocalListener(
"mq:emptyQueue:preIndexQueue",
emptyQueueHandler,
);
await this.clientSystem.markPreIndexComplete();
await this.clientSystem.reloadState();
// Queue all pages for full indexing
await this.mq.batchSend(
"indexQueue",
(await space.fetchPageList()).map((pm) => pm.name + ".md"),
);
await this.mq.awaitEmptyQueue("indexQueue");
}
};
this.eventHook.addLocalListener(
"mq:emptyQueue:preIndexQueue",
emptyQueueHandler,
);
let lastSaveTimestamp: number | undefined;
const updateLastSaveTimestamp = () => {
@@ -580,7 +608,7 @@ export class Client {
console.log("Updating page list cache");
// Check if the initial sync has been completed
const initialIndexCompleted = await this.clientSystem
.hasFullIndexCompleted();
.hasPreIndexCompleted();
let allPages: PageMeta[] = [];
@@ -1101,7 +1129,7 @@ export class Client {
// Fetch the meta which includes the possibly indexed stuff, like page
// decorations
if (await this.clientSystem.hasFullIndexCompleted()) {
if (await this.clientSystem.hasPreIndexCompleted()) {
try {
const enrichedMeta = await this.clientSystem.getObjectByRef<PageMeta>(
pageName,
@@ -1246,7 +1274,7 @@ export class Client {
console.warn("Not loading custom styles, since space style is disabled");
return;
}
if (!await this.clientSystem.hasFullIndexCompleted()) {
if (!await this.clientSystem.hasPreIndexCompleted()) {
return;
}
+4 -5
View File
@@ -201,7 +201,7 @@ export class ClientSystem {
console.info("Space Lua scripts are disabled, skipping loading scripts");
return;
}
if (!await this.hasFullIndexCompleted()) {
if (!await this.hasPreIndexCompleted()) {
console.info(
"Not loading space scripts, since initial indexing has not completed yet",
);
@@ -294,7 +294,6 @@ export class ClientSystem {
if (!currentIndexVersion) {
console.log("No index version found, assuming fresh install");
await this.markFullSpaceIndexComplete();
return;
}
@@ -309,7 +308,7 @@ export class ClientSystem {
await this.setIndexOngoing();
await this.system.invokeFunction("index.reindexSpace", []);
console.info("[index]", "Full space index complete.");
await this.markFullSpaceIndexComplete();
await this.markPreIndexComplete();
await this.setIndexOngoing(false);
// Let's load space scripts again, which probably weren't loaded before
await this.reloadState();
@@ -325,7 +324,7 @@ export class ClientSystem {
this.client.rebuildEditorState();
}
public async hasFullIndexCompleted() {
public async hasPreIndexCompleted() {
return (await this.ds.get(indexVersionKey)) === desiredIndexVersion;
}
@@ -333,7 +332,7 @@ export class ClientSystem {
return this.ds.get(indexVersionKey);
}
async markFullSpaceIndexComplete() {
async markPreIndexComplete() {
await this.ds.set(indexVersionKey, desiredIndexVersion);
}
}
+5
View File
@@ -109,6 +109,11 @@ export class EncryptedKvPrimitives implements KvPrimitives {
}
}
async countQuery({ prefix }: KvQueryOptions): Promise<number> {
const encryptedPrefix = prefix ? await this.encryptKey(prefix) : undefined;
return this.wrapped.countQuery({ prefix: encryptedPrefix });
}
close() {
this.wrapped.close();
}
+9
View File
@@ -79,6 +79,15 @@ export class IndexedDBKvPrimitives implements KvPrimitives {
}
}
countQuery({ prefix }: KvQueryOptions): Promise<number> {
const tx = this.db.transaction(objectStoreName, "readonly");
prefix = prefix || [];
return tx.store.count(IDBKeyRange.bound(
this.buildKey([...prefix, ""]),
this.buildKey([...prefix, "\uffff"]),
));
}
close() {
this.db.close();
}
+5
View File
@@ -13,6 +13,11 @@ export interface KvPrimitives {
query<T = any>(options: KvQueryOptions): AsyncIterableIterator<KV<T>>;
/**
* A more efficient way to do counts
*/
countQuery(options: KvQueryOptions): Promise<number>;
// Completely clear all data from this datastore
clear(): Promise<void>;
+8
View File
@@ -144,6 +144,14 @@ export class MemoryKvPrimitives implements KvPrimitives {
}
}
countQuery({ prefix }: KvQueryOptions): Promise<number> {
const prefixStr = prefix ? prefix.join(memoryKeySeparator) : undefined;
const keys = [...this.store.keys()];
return Promise.resolve(
keys.filter((key) => !prefixStr || key.startsWith(prefixStr)).length,
);
}
async close(): Promise<void> {
// Force immediate persistence when closing
if (this.filePath) {
+13 -2
View File
@@ -5,14 +5,21 @@ import { DataStore } from "./datastore.ts";
import { FakeTime } from "@std/testing/time";
import type { MQMessage } from "../../plug-api/types/datastore.ts";
import { EventHook } from "../plugos/hooks/event.ts";
import { System } from "../plugos/system.ts";
import type { EventHookT } from "@silverbulletmd/silverbullet/type/manifest";
Deno.test("DataStore MQ", async () => {
const time = new FakeTime();
const db = new MemoryKvPrimitives(); // In-memory only, no persistence
const eventHook = new EventHook();
const system = new System<EventHookT>();
system.addHook(eventHook);
try {
const mq = new DataStoreMQ(
new DataStore(db),
eventHook,
);
let messages: MQMessage[];
@@ -32,8 +39,8 @@ Deno.test("DataStore MQ", async () => {
await time.tickAsync(20);
await mq.requeueTimeouts(10);
messages = await mq.poll("test", 10);
const stats = await mq.getAllQueueStats();
assertEquals(stats["test"].processing, 1);
const stats = await mq.getQueueStats();
assertEquals(stats.processing, 1);
assertEquals(messages.length, 1);
assertEquals(messages[0].retries, 1);
@@ -77,10 +84,14 @@ Deno.test("DataStore MQ", async () => {
Deno.test("DataStore MQ - Scale test with multiple subscribers", async () => {
const time = new FakeTime();
const db = new MemoryKvPrimitives();
const eventHook = new EventHook();
const system = new System<EventHookT>();
system.addHook(eventHook);
try {
const mq = new DataStoreMQ(
new DataStore(db),
eventHook,
);
const queueName = "scale-test";
+16 -57
View File
@@ -9,6 +9,7 @@ import type {
MQSubscribeOptions,
} from "../../plug-api/types/datastore.ts";
import { race, sleep } from "@silverbulletmd/silverbullet/lib/async";
import type { EventHook } from "../plugos/hooks/event.ts";
export type ProcessingMessage = MQMessage & {
ts: number;
@@ -49,6 +50,10 @@ export class QueueWorker {
await this.callback(messages);
} else {
// No messages, wait to be woken up or a timeout
this.mq.eventHook.dispatchEvent(
`mq:emptyQueue:${this.queue}`,
this.queue,
);
try {
await race([
// Wait to be woken up explicitly
@@ -98,6 +103,7 @@ export class DataStoreMQ {
constructor(
private ds: DataStore,
public eventHook: EventHook,
) {
}
@@ -350,12 +356,16 @@ export class DataStoreMQ {
await this.ds.batchDelete(ids);
}
async getQueueStats(queue: string): Promise<MQStats> {
const queued =
(await (this.ds.luaQuery([...queuedPrefix, queue], {}))).length;
const processing =
(await (this.ds.luaQuery([...processingPrefix, queue], {}))).length;
const dlq = (await (this.ds.luaQuery([...dlqPrefix, queue], {}))).length;
async getQueueStats(queue?: string): Promise<MQStats> {
const queued = await this.ds.kv.countQuery({
prefix: queue ? [...queuedPrefix, queue] : queuedPrefix,
});
const processing = await this.ds.kv.countQuery({
prefix: queue ? [...processingPrefix, queue] : processingPrefix,
});
const dlq = await this.ds.kv.countQuery({
prefix: queue ? [...dlqPrefix, queue] : dlqPrefix,
});
return {
queued,
processing,
@@ -372,55 +382,4 @@ export class DataStoreMQ {
await sleep(200);
}
}
async getAllQueueStats(): Promise<Record<string, MQStats>> {
const allStatus: Record<string, MQStats> = {};
for (
const message of await this.ds.luaQuery<MQMessage>(
queuedPrefix,
{},
)
) {
if (!allStatus[message.queue]) {
allStatus[message.queue] = {
queued: 0,
processing: 0,
dlq: 0,
};
}
allStatus[message.queue].queued++;
}
for (
const message of await this.ds.luaQuery<MQMessage>(
processingPrefix,
{},
)
) {
if (!allStatus[message.queue]) {
allStatus[message.queue] = {
queued: 0,
processing: 0,
dlq: 0,
};
}
allStatus[message.queue].processing++;
}
for (
const message of await this.ds.luaQuery<MQMessage>(
dlqPrefix,
{},
)
) {
if (!allStatus[message.queue]) {
allStatus[message.queue] = {
queued: 0,
processing: 0,
dlq: 0,
};
}
allStatus[message.queue].dlq++;
}
return allStatus;
}
}
+3 -1
View File
@@ -114,7 +114,9 @@ export class MainUI {
updateTheme();
if (viewState.uiOptions.darkMode === undefined) {
const mediaQuery = globalThis.matchMedia("(prefers-color-scheme: dark)");
const mediaQuery = globalThis.matchMedia(
"(prefers-color-scheme: dark)",
);
mediaQuery.addEventListener("change", updateTheme);
return () => {
+638 -640
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -58,7 +58,7 @@ export function batchAck(queue: string, ids: string[]): Promise<void> {
* Retrieves stats on a particular queue.
* @param queue the name of the queue
*/
export function getQueueStats(queue: string): Promise<MQStats> {
export function getQueueStats(queue?: string): Promise<MQStats> {
return syscall("mq.getQueueStats", queue);
}
-1
View File
@@ -3,7 +3,6 @@ import type { EventSubscriptionDef } from "./manifest.ts";
export type IndexTreeEvent = {
name: string;
tree: ParseTree;
};
+17 -7
View File
@@ -32,6 +32,7 @@ functions:
path: api.ts:clearFileIndex
events:
- file:deleted
- file:clearindex
reindexSpaceCommand:
path: "./command.ts:reindexCommand"
@@ -46,6 +47,13 @@ functions:
batchSize: 3
autoAck: true
processPreIndexQueue:
path: ./queue.ts:processPreIndexQueue
mqSubscriptions:
- queue: preIndexQueue
batchSize: 5
autoAck: true
reindexSpace:
path: "./queue.ts:reindexSpace"
@@ -59,6 +67,11 @@ functions:
events:
- page:index
preIndexPage:
path: page.ts:preIndexPage
events:
- page:preindex
indexParagraphs:
path: "./paragraph.ts:indexParagraphs"
events:
@@ -98,27 +111,24 @@ functions:
events:
- page:index
# Script
indexSpaceScript:
path: script.ts:indexSpaceScript
events:
- page:index
# Lua
indexSpaceLua:
path: script.ts:indexSpaceLua
events:
- page:index
- page:preindex
# Style
indexSpaceStyle:
path: style.ts:indexSpaceStyle
events:
- page:index
- page:preindex
# Hashtags
indexTags:
path: tags.ts:indexTags
events:
- page:index
tagComplete:
path: tags.ts:tagComplete
events:
+14 -4
View File
@@ -25,11 +25,12 @@ import type { AspiringPageObject } from "./page_links.ts";
import type { PageMeta } from "@silverbulletmd/silverbullet/type/index";
import type { LintDiagnostic } from "@silverbulletmd/silverbullet/type/client";
export async function indexPage({ name, tree }: IndexTreeEvent) {
export async function preIndexPage({ name, tree }: IndexTreeEvent) {
if (name.startsWith("_")) {
// Don't index pages starting with _
return;
}
const pageMeta = await space.getPageMeta(name);
const frontmatter = await extractFrontMatter(tree);
const toplevelAttributes = await extractAttributes(tree);
@@ -65,7 +66,19 @@ export async function indexPage({ name, tree }: IndexTreeEvent) {
updateITags(combinedPageMeta, frontmatter);
// console.log("Page object", combinedPageMeta);
await indexObjects<PageMeta>(name, [combinedPageMeta]);
}
// Most interesting indexing for pages happens in the preindex phase, here we're just cleaning up aspiring pages
export async function indexPage({ name }: IndexTreeEvent) {
if (name.startsWith("_")) {
// Don't index pages starting with _
return;
}
// Make sure this page is no (longer) in the aspiring pages list
// TODO: This can possibly done more optimally
const aspiringPages = await queryLuaObjects<AspiringPageObject>(
"aspiring-page",
{
@@ -78,9 +91,6 @@ export async function indexPage({ name, tree }: IndexTreeEvent) {
console.log("Deleting aspiring page", aspiringPage);
await deleteObject("aspiring-page", aspiringPage.page, aspiringPage.ref);
}
// console.log("Page object", combinedPageMeta);
await indexObjects<PageMeta>(name, [combinedPageMeta]);
}
export async function lintFrontmatter(): Promise<LintDiagnostic[]> {
+64 -29
View File
@@ -9,7 +9,8 @@ import {
import { sleep } from "@silverbulletmd/silverbullet/lib/async";
import type { MQMessage } from "@silverbulletmd/silverbullet/type/datastore";
import type { IndexTreeEvent } from "@silverbulletmd/silverbullet/type/event";
import { clearFileIndex } from "./api.ts";
const uiUpdateInterval = 5000;
export async function reindexSpace() {
if (await system.getMode() === "ro") {
@@ -25,8 +26,10 @@ export async function reindexSpace() {
console.log("Queing", files.length, "pages to be indexed.");
// Queue all file names to be indexed
await mq.batchSend("preIndexQueue", files.map((file) => file.name));
await mq.batchSend("indexQueue", files.map((file) => file.name));
await editor.showProgress(0, "index");
// We'll assume this one completes last
await mq.awaitEmptyQueue("indexQueue");
// And notify the user
@@ -34,56 +37,88 @@ export async function reindexSpace() {
await editor.showProgress();
}
setTimeout(updateIndexProgressInUI, 5000);
setTimeout(updateIndexProgressInUI, uiUpdateInterval);
async function totalItemsQueued() {
const queueStats = await mq.getQueueStats();
return queueStats.queued + queueStats.processing;
}
async function updateIndexProgressInUI() {
// Let's see if there's anything in the index queue
let queueStats = await mq.getQueueStats("indexQueue");
if (queueStats.queued > 0 || queueStats.processing > 0) {
let totalQueued = await totalItemsQueued();
if (totalQueued > 0) {
// Something's queued, likely it makes sense to compare this to the total number of files (progress wise)
const fileList = await space.listFiles();
while (queueStats.queued > 0 || queueStats.processing > 0) {
queueStats = await mq.getQueueStats("indexQueue");
const percentage = Math.round(
(fileList.length - queueStats.queued) / fileList.length * 100,
while (totalQueued > 0) {
totalQueued = await totalItemsQueued();
let percentage = Math.round(
(fileList.length - totalQueued) / fileList.length * 100,
);
if (percentage < 0) {
// The assumption that the queue size is related tot he file list length turns out to be wrong
// // Let's show some sort of number
percentage = 67;
}
if (percentage > 99) {
// Hide progress circle
await editor.showProgress();
} else {
await editor.showProgress(percentage, "index");
}
// Update UI every second
await sleep(1000);
}
}
// Schedule again
setTimeout(updateIndexProgressInUI, 5000);
setTimeout(updateIndexProgressInUI, uiUpdateInterval);
}
export async function processIndexQueue(messages: MQMessage[]) {
for (const message of messages) {
let name: string = message.body;
console.log(`Indexing file ${name}`);
if (name.endsWith(".md")) {
name = name.slice(0, -3);
await indexPage(name);
} else {
await events.dispatchEvent("document:index", name);
}
const path: string = message.body;
console.log("[index]", `Indexing file ${path}`);
await indexFile(path);
}
}
async function indexPage(name: string) {
// Clear any previous index entries for this file
await clearFileIndex(name);
// Read and parse the file
const text = await space.readPage(name);
const parsed = await markdown.parseMarkdown(text);
async function indexFile(path: string) {
if (path.endsWith(".md")) {
// Page
const name = path.slice(0, -3);
// Read and parse the file
const text = await space.readPage(name);
const tree = await markdown.parseMarkdown(text);
// Emit the event which will be picked up by indexers
await events.dispatchEvent("page:index", {
name,
tree: parsed,
} as IndexTreeEvent);
// Emit the event which will be picked up by indexers
await events.dispatchEvent("page:index", {
name,
tree,
} as IndexTreeEvent);
}
}
export async function processPreIndexQueue(messages: MQMessage[]) {
for (const message of messages) {
const path: string = message.body;
console.log("[pre-index]", `Pre-indexing file ${path}`);
await preIndexFile(path);
}
}
async function preIndexFile(path: string) {
if (path.endsWith(".md")) {
// Page
const name = path.slice(0, -3);
// Read file
const text = await space.readPage(name);
const tree = await markdown.parseMarkdown(text);
// Emit the event which will be picked up by indexers
await events.dispatchEvent("page:preindex", {
name,
tree,
} as IndexTreeEvent);
} else {
await events.dispatchEvent("document:index", path);
}
}
-26
View File
@@ -11,32 +11,6 @@ export type ScriptObject = ObjectValue<{
priority?: number;
}>;
export async function indexSpaceScript({ name, tree }: IndexTreeEvent) {
const allScripts: ScriptObject[] = [];
collectNodesOfType(tree, "FencedCode").map((t) => {
const codeInfoNode = findNodeOfType(t, "CodeInfo");
if (!codeInfoNode) {
return;
}
const fenceType = codeInfoNode.children![0].text!;
if (fenceType !== "space-script") {
return;
}
const codeTextNode = findNodeOfType(t, "CodeText");
if (!codeTextNode) {
// Honestly, this shouldn't happen
return;
}
const codeText = codeTextNode.children![0].text!;
allScripts.push({
ref: `${name}@${t.from!}`,
tag: "space-script",
script: codeText,
});
});
await indexObjects<ScriptObject>(name, allScripts);
}
export async function indexSpaceLua({ name, tree }: IndexTreeEvent) {
const allScripts: ScriptObject[] = [];
collectNodesOfType(tree, "FencedCode").map((t) => {