mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
UI watcher
This commit is contained in:
1 parent
a760a152dc
commit
b8a9721f1f
7 files changed
+224
-39
No files matched your search
@@ -4,6 +4,7 @@ const VERSION_KEY = "betterseqta-index-version";
|
||||
|
||||
let dbPromise: Promise<IDBDatabase> | null = null;
|
||||
let cachedDb: IDBDatabase | null = null;
|
||||
let upgradeChain: Promise<void> = Promise.resolve();
|
||||
|
||||
function getCurrentVersion(): number {
|
||||
const storedVersion = localStorage.getItem(VERSION_KEY);
|
||||
@@ -180,48 +181,161 @@ function idbRequest<T>(request: IDBRequest<T>): Promise<T> {
|
||||
});
|
||||
}
|
||||
|
||||
async function objectStore(
|
||||
function runStoreTransaction(
|
||||
db: IDBDatabase,
|
||||
store: string,
|
||||
mode: IDBTransactionMode = "readonly",
|
||||
): Promise<IDBObjectStore> {
|
||||
const db = await openDB();
|
||||
mode: IDBTransactionMode,
|
||||
run: (objectStore: IDBObjectStore) => void | Promise<void>,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(store, mode);
|
||||
const objectStoreRef = tx.objectStore(store);
|
||||
|
||||
if (!db.objectStoreNames.contains(store)) {
|
||||
await upgradeDB(store);
|
||||
const upgradedDb = await openDB();
|
||||
return upgradedDb.transaction(store, mode).objectStore(store);
|
||||
Promise.resolve(run(objectStoreRef)).catch(reject);
|
||||
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error ?? new Error(`IndexedDB transaction failed for ${store}`));
|
||||
tx.onabort = () => reject(tx.error ?? new Error(`IndexedDB transaction aborted for ${store}`));
|
||||
});
|
||||
}
|
||||
|
||||
async function withUpgradeLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const previous = upgradeChain;
|
||||
let release!: () => void;
|
||||
upgradeChain = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
await previous;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
return db.transaction(store, mode).objectStore(store);
|
||||
async function openDatabaseWithStores(
|
||||
version: number,
|
||||
storesToCreate: string[],
|
||||
): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let request: IDBOpenDBRequest;
|
||||
try {
|
||||
request = indexedDB.open(DB_NAME, version);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(META_STORE)) {
|
||||
db.createObjectStore(META_STORE);
|
||||
}
|
||||
for (const store of storesToCreate) {
|
||||
if (!db.objectStoreNames.contains(store)) {
|
||||
db.createObjectStore(store);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
attachConnection(request.result);
|
||||
resolve(request.result);
|
||||
};
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
async function upgradeDB(newStore: string): Promise<void> {
|
||||
invalidateConnection();
|
||||
await withUpgradeLock(async () => {
|
||||
invalidateConnection();
|
||||
|
||||
let baseVersion = 0;
|
||||
let baseVersion = 0;
|
||||
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
baseVersion = db.version;
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
if (db.objectStoreNames.contains(newStore)) {
|
||||
attachConnection(db);
|
||||
return;
|
||||
}
|
||||
baseVersion = db.version;
|
||||
db.close();
|
||||
cachedDb = null;
|
||||
dbPromise = null;
|
||||
} catch (error) {
|
||||
console.warn("[DB] Could not probe database version before upgrade:", error);
|
||||
}
|
||||
|
||||
try {
|
||||
await openDatabaseWithStores(baseVersion + 1, [newStore]);
|
||||
} catch (error) {
|
||||
console.error("Error upgrading database:", error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates any missing object stores in a single version bump so later job
|
||||
* writes do not race passive observer traffic on a mid-run upgrade.
|
||||
*/
|
||||
export async function ensureStoresExist(stores: string[]): Promise<void> {
|
||||
const uniqueStores = [...new Set(stores.filter(Boolean))];
|
||||
if (uniqueStores.length === 0) return;
|
||||
|
||||
await withUpgradeLock(async () => {
|
||||
let db: IDBDatabase;
|
||||
try {
|
||||
db = await openDB();
|
||||
} catch (error) {
|
||||
console.warn("[DB] ensureStoresExist: could not open database:", error);
|
||||
return;
|
||||
}
|
||||
|
||||
const missing = uniqueStores.filter(
|
||||
(store) => !db.objectStoreNames.contains(store),
|
||||
);
|
||||
if (missing.length === 0) return;
|
||||
|
||||
invalidateConnection();
|
||||
const baseVersion = db.version;
|
||||
db.close();
|
||||
cachedDb = null;
|
||||
dbPromise = null;
|
||||
} catch (error) {
|
||||
console.warn("[DB] Could not probe database version before upgrade:", error);
|
||||
|
||||
try {
|
||||
await openDatabaseWithStores(baseVersion + 1, missing);
|
||||
} catch (error) {
|
||||
console.error("[DB] ensureStoresExist failed:", error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function withObjectStore<T>(
|
||||
store: string,
|
||||
mode: IDBTransactionMode,
|
||||
run: (objectStore: IDBObjectStore) => Promise<T>,
|
||||
): Promise<T> {
|
||||
let db = await openDB();
|
||||
|
||||
if (!db.objectStoreNames.contains(store)) {
|
||||
await upgradeDB(store);
|
||||
db = await openDB();
|
||||
}
|
||||
|
||||
try {
|
||||
await openDatabase(baseVersion + 1, newStore);
|
||||
} catch (error) {
|
||||
console.error("Error upgrading database:", error);
|
||||
throw error;
|
||||
}
|
||||
let result!: T;
|
||||
await runStoreTransaction(db, store, mode, async (objectStoreRef) => {
|
||||
result = await run(objectStoreRef);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function getAll(store: string): Promise<any[]> {
|
||||
try {
|
||||
const s = await objectStore(store);
|
||||
return await idbRequest(s.getAll());
|
||||
return await withObjectStore(store, "readonly", async (s) =>
|
||||
idbRequest(s.getAll()),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`Error in getAll for store ${store}:`, error);
|
||||
return [];
|
||||
@@ -230,8 +344,9 @@ export async function getAll(store: string): Promise<any[]> {
|
||||
|
||||
export async function get(store: string, key: string): Promise<any> {
|
||||
try {
|
||||
const s = await objectStore(store);
|
||||
return await idbRequest(s.get(key));
|
||||
return await withObjectStore(store, "readonly", async (s) =>
|
||||
idbRequest(s.get(key)),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`Error in get for store ${store}, key ${key}:`, error);
|
||||
return null;
|
||||
@@ -244,8 +359,9 @@ export async function put(
|
||||
key?: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const s = await objectStore(store, "readwrite");
|
||||
await idbRequest(key ? s.put(value, key) : s.put(value));
|
||||
await withObjectStore(store, "readwrite", async (s) => {
|
||||
await idbRequest(key ? s.put(value, key) : s.put(value));
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Error in put for store ${store}:`, error);
|
||||
throw error;
|
||||
@@ -297,8 +413,9 @@ function runStoreDiffTransaction(
|
||||
|
||||
export async function remove(store: string, key: string): Promise<void> {
|
||||
try {
|
||||
const s = await objectStore(store, "readwrite");
|
||||
await idbRequest(s.delete(key));
|
||||
await withObjectStore(store, "readwrite", async (s) => {
|
||||
await idbRequest(s.delete(key));
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Error in remove for store ${store}, key ${key}:`, error);
|
||||
throw error;
|
||||
@@ -307,8 +424,9 @@ export async function remove(store: string, key: string): Promise<void> {
|
||||
|
||||
export async function clear(store: string): Promise<void> {
|
||||
try {
|
||||
const s = await objectStore(store, "readwrite");
|
||||
await idbRequest(s.clear());
|
||||
await withObjectStore(store, "readwrite", async (s) => {
|
||||
await idbRequest(s.clear());
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Error in clear for store ${store}:`, error);
|
||||
throw error;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { applyStoreDiff, get, getAll, put, remove } from "./db";
|
||||
import { applyStoreDiff, ensureStoresExist, get, getAll, put, remove } from "./db";
|
||||
import { jobs } from "./jobs";
|
||||
import { decorateIndexItems } from "./renderComponents";
|
||||
import type { IndexItem, Job, JobContext } from "./types";
|
||||
@@ -8,6 +8,7 @@ import { getVectorizedItemIds, pruneOrphanVectorEmbeddings } from "./utils";
|
||||
import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion";
|
||||
import { resetSearchIndexes } from "./resetIndexes";
|
||||
import { isIndexingPaused } from "./indexingPause";
|
||||
import { setIndexingActive } from "./indexingState";
|
||||
|
||||
import { verboseDebug } from '@/utils/verboseLog';
|
||||
const META_STORE = "meta";
|
||||
@@ -304,10 +305,13 @@ export async function runIndexing(): Promise<void> {
|
||||
}
|
||||
|
||||
startHeartbeat();
|
||||
setIndexingActive(true);
|
||||
verboseDebug("%c[Indexer] Starting indexing...", "color: green");
|
||||
|
||||
try {
|
||||
const jobIds = Object.keys(jobs);
|
||||
await ensureStoresExist([META_STORE, ...jobIds]);
|
||||
|
||||
let completedJobs = 0;
|
||||
const totalSteps = jobIds.length + 1;
|
||||
dispatchProgress(completedJobs, totalSteps, true, "Starting jobs");
|
||||
@@ -379,6 +383,15 @@ export async function runIndexing(): Promise<void> {
|
||||
removeItem,
|
||||
getProgress: () => loadProgress(jobId),
|
||||
setProgress: (p) => saveProgress(jobId, p),
|
||||
reportJobProgress: ({ processed, total, status }) => {
|
||||
const stepProgress = total > 0 ? processed / total : 0;
|
||||
dispatchProgress(
|
||||
completedJobs + stepProgress,
|
||||
totalSteps,
|
||||
true,
|
||||
status ?? `Running job: ${job.label}`,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff");
|
||||
@@ -500,6 +513,7 @@ export async function runIndexing(): Promise<void> {
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIndexingActive(false);
|
||||
stopHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import {
|
||||
isIndexingActive,
|
||||
setIndexingActive,
|
||||
} from "./indexingState";
|
||||
|
||||
describe("indexingState", () => {
|
||||
afterEach(() => {
|
||||
setIndexingActive(false);
|
||||
});
|
||||
|
||||
it("tracks whether structured indexing is running", () => {
|
||||
expect(isIndexingActive()).toBe(false);
|
||||
setIndexingActive(true);
|
||||
expect(isIndexingActive()).toBe(true);
|
||||
setIndexingActive(false);
|
||||
expect(isIndexingActive()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
/** True while `runIndexing()` holds the indexer lock in this tab. */
|
||||
let indexingActive = false;
|
||||
|
||||
export function setIndexingActive(active: boolean): void {
|
||||
indexingActive = active;
|
||||
}
|
||||
|
||||
export function isIndexingActive(): boolean {
|
||||
return indexingActive;
|
||||
}
|
||||
@@ -104,7 +104,7 @@ export const coursesJob: Job = {
|
||||
return score;
|
||||
},
|
||||
|
||||
run: async (_ctx) => {
|
||||
run: async (ctx) => {
|
||||
const subjects = await fetchActiveSubjects();
|
||||
if (subjects.length === 0) {
|
||||
verboseDebug("[Courses job] No active subjects discovered.");
|
||||
@@ -113,6 +113,8 @@ export const coursesJob: Job = {
|
||||
|
||||
const items: IndexItem[] = [];
|
||||
const seenIds = new Set<string>();
|
||||
const totalSubjects = subjects.length;
|
||||
let processedSubjects = 0;
|
||||
|
||||
// Sequential per-subject fetch keeps load on SEQTA bounded; the shared
|
||||
// API layer also limits concurrency per route as a defense in depth.
|
||||
@@ -121,6 +123,12 @@ export const coursesJob: Job = {
|
||||
if (seenIds.has(id)) continue;
|
||||
seenIds.add(id);
|
||||
|
||||
ctx.reportJobProgress?.({
|
||||
processed: processedSubjects,
|
||||
total: totalSubjects,
|
||||
status: `Running job: Courses (${processedSubjects + 1}/${totalSubjects})`,
|
||||
});
|
||||
|
||||
const payload = await seqtaFetchPayload<CoursePayload>(
|
||||
"/seqta/student/load/courses",
|
||||
{
|
||||
@@ -129,7 +137,10 @@ export const coursesJob: Job = {
|
||||
},
|
||||
);
|
||||
|
||||
if (!payload) continue;
|
||||
if (!payload) {
|
||||
processedSubjects++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const title =
|
||||
(typeof payload.t === "string" && payload.t.trim()) ||
|
||||
@@ -168,8 +179,15 @@ export const coursesJob: Job = {
|
||||
renderComponentId: "course",
|
||||
}),
|
||||
);
|
||||
processedSubjects++;
|
||||
}
|
||||
|
||||
ctx.reportJobProgress?.({
|
||||
processed: totalSubjects,
|
||||
total: totalSubjects,
|
||||
status: "Running job: Courses (saving)",
|
||||
});
|
||||
|
||||
verboseDebug(
|
||||
`[Courses job] Indexed ${items.length} courses across ${subjects.length} subjects.`,
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { isSensitiveSeqtaPath, normalizeSeqtaPath } from "./api";
|
||||
import { mergeDynamicItems } from "../utils/dynamicItems";
|
||||
import { decorateIndexItems } from "./renderComponents";
|
||||
import { isIndexingPaused } from "./indexingPause";
|
||||
import { isIndexingActive } from "./indexingState";
|
||||
import { isAssessmentListRoute } from "./routeFilters";
|
||||
|
||||
/**
|
||||
@@ -384,7 +385,7 @@ function synthesizeItems(
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function persistItems(items: IndexItem[]): Promise<void> {
|
||||
if (items.length === 0 || isIndexingPaused()) return;
|
||||
if (items.length === 0 || isIndexingPaused() || isIndexingActive()) return;
|
||||
|
||||
// Dedupe against existing entries. We replace on collision so the latest
|
||||
// observation wins (e.g. if a message changes title).
|
||||
@@ -405,10 +406,10 @@ async function persistItems(items: IndexItem[]): Promise<void> {
|
||||
}
|
||||
|
||||
function scheduleFlush() {
|
||||
if (pendingFlush || isIndexingPaused()) return;
|
||||
if (pendingFlush || isIndexingPaused() || isIndexingActive()) return;
|
||||
pendingFlush = setTimeout(() => {
|
||||
pendingFlush = null;
|
||||
if (!pendingDirty || isIndexingPaused()) return;
|
||||
if (!pendingDirty || isIndexingPaused() || isIndexingActive()) return;
|
||||
pendingDirty = false;
|
||||
void flushDynamicItems();
|
||||
}, FLUSH_DEBOUNCE_MS);
|
||||
@@ -425,7 +426,7 @@ export function pausePassiveObserver(): void {
|
||||
}
|
||||
|
||||
async function flushDynamicItems(): Promise<void> {
|
||||
if (isIndexingPaused()) return;
|
||||
if (isIndexingPaused() || isIndexingActive()) return;
|
||||
if (pendingChangedItems.size === 0) return;
|
||||
|
||||
const rawChanged = Array.from(pendingChangedItems.values());
|
||||
|
||||
@@ -24,6 +24,12 @@ export interface JobContext {
|
||||
removeItem: (id: string, storeId?: string) => Promise<void>;
|
||||
getProgress: <T = any>() => Promise<T | undefined>;
|
||||
setProgress: <T = any>(progress: T) => Promise<void>;
|
||||
/** Optional live status/progress while a long-running job is in flight. */
|
||||
reportJobProgress?: (detail: {
|
||||
processed: number;
|
||||
total: number;
|
||||
status?: string;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
|
||||
Reference in new issue
Block a user