@spooky-sync/core 0.0.1-canary.8 → 0.0.1-canary.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +56 -0
- package/dist/index.d.ts +854 -339
- package/dist/index.js +2633 -396
- package/dist/otel/index.d.ts +21 -0
- package/dist/otel/index.js +86 -0
- package/dist/types.d.ts +494 -0
- package/package.json +39 -9
- package/skills/sp00ky-core/SKILL.md +258 -0
- package/skills/sp00ky-core/references/auth.md +98 -0
- package/skills/sp00ky-core/references/config.md +76 -0
- package/src/build-globals.d.ts +12 -0
- package/src/events/events.test.ts +2 -1
- package/src/events/index.ts +3 -0
- package/src/index.ts +9 -2
- package/src/modules/auth/events/index.ts +2 -1
- package/src/modules/auth/index.ts +59 -20
- package/src/modules/cache/index.ts +41 -29
- package/src/modules/cache/types.ts +2 -2
- package/src/modules/crdt/crdt-field.ts +281 -0
- package/src/modules/crdt/crdt-hydration.test.ts +206 -0
- package/src/modules/crdt/index.ts +352 -0
- package/src/modules/data/data.status.test.ts +108 -0
- package/src/modules/data/index.ts +726 -108
- package/src/modules/data/window-query.test.ts +52 -0
- package/src/modules/data/window-query.ts +130 -0
- package/src/modules/devtools/index.ts +89 -21
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +81 -0
- package/src/modules/feature-flag/index.ts +166 -0
- package/src/modules/ref-tables.test.ts +56 -0
- package/src/modules/ref-tables.ts +57 -0
- package/src/modules/sync/engine.ts +97 -37
- package/src/modules/sync/events/index.ts +3 -2
- package/src/modules/sync/queue/queue-down.ts +5 -4
- package/src/modules/sync/queue/queue-up.ts +14 -13
- package/src/modules/sync/scheduler.ts +2 -2
- package/src/modules/sync/sync.ts +676 -58
- package/src/modules/sync/utils.test.ts +269 -2
- package/src/modules/sync/utils.ts +182 -17
- package/src/otel/index.ts +127 -0
- package/src/services/database/database.ts +11 -11
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/local-migrator.ts +21 -21
- package/src/services/database/local.test.ts +33 -0
- package/src/services/database/local.ts +192 -32
- package/src/services/database/remote.ts +13 -13
- package/src/services/logger/index.ts +6 -101
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +41 -0
- package/src/services/persistence/surrealdb.ts +9 -9
- package/src/services/stream-processor/index.ts +248 -37
- package/src/services/stream-processor/permissions.test.ts +47 -0
- package/src/services/stream-processor/permissions.ts +53 -0
- package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +18 -2
- package/src/sp00ky.auth-order.test.ts +65 -0
- package/src/sp00ky.ts +625 -0
- package/src/types.ts +140 -13
- package/src/utils/index.ts +35 -13
- package/src/utils/parser.ts +3 -2
- package/src/utils/surql.ts +24 -15
- package/src/utils/withRetry.test.ts +1 -1
- package/tsdown.config.ts +55 -1
- package/src/spooky.ts +0 -392
package/dist/index.js
CHANGED
|
@@ -2,13 +2,14 @@ import { DateTime, Duration, RecordId, Surreal, Uuid, applyDiagnostics, createRe
|
|
|
2
2
|
import { QueryBuilder, RecordId as RecordId$1 } from "@spooky-sync/query-builder";
|
|
3
3
|
import { createWasmWorkerEngines } from "@surrealdb/wasm";
|
|
4
4
|
import pino from "pino";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
8
|
-
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
|
|
9
|
-
import { createContextKey } from "@opentelemetry/api";
|
|
10
|
-
import init, { SpookyProcessor } from "@spooky-sync/ssp-wasm";
|
|
5
|
+
import init, { Sp00kyProcessor } from "@spooky-sync/ssp-wasm";
|
|
6
|
+
import { LoroDoc } from "loro-crdt";
|
|
11
7
|
|
|
8
|
+
//#region src/types.ts
|
|
9
|
+
/** Cap on the rolling materialization-sample window kept per query in memory. */
|
|
10
|
+
const MATERIALIZATION_SAMPLE_WINDOW = 100;
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
12
13
|
//#region src/utils/surql.ts
|
|
13
14
|
const surql = {
|
|
14
15
|
seal(query, options) {
|
|
@@ -33,7 +34,7 @@ const surql = {
|
|
|
33
34
|
return `SELECT ${returnValues.join(",")} FROM ONLY $${idVar}`;
|
|
34
35
|
},
|
|
35
36
|
selectByFieldsAnd(table, whereVar, returnValues) {
|
|
36
|
-
return `SELECT ${returnValues.map((
|
|
37
|
+
return `SELECT ${returnValues.map((rv) => typeof rv === "string" ? rv : `${rv.field} as ${rv.alias}`).join(",")} FROM ${table} WHERE ${whereVar.map((wv) => typeof wv === "string" ? `${wv} = $${wv}` : `${wv.field} = $${wv.variable}`).join(" AND ")}`;
|
|
37
38
|
},
|
|
38
39
|
create(idVar, dataVar) {
|
|
39
40
|
return `CREATE ONLY $${idVar} CONTENT $${dataVar}`;
|
|
@@ -44,11 +45,14 @@ const surql = {
|
|
|
44
45
|
upsert(idVar, dataVar) {
|
|
45
46
|
return `UPSERT ONLY $${idVar} REPLACE $${dataVar}`;
|
|
46
47
|
},
|
|
48
|
+
upsertMerge(idVar, dataVar) {
|
|
49
|
+
return `UPSERT ONLY $${idVar} MERGE $${dataVar}`;
|
|
50
|
+
},
|
|
47
51
|
updateMerge(idVar, dataVar) {
|
|
48
52
|
return `UPDATE ONLY $${idVar} MERGE $${dataVar}`;
|
|
49
53
|
},
|
|
50
54
|
updateSet(idVar, keyDataVar) {
|
|
51
|
-
return `UPDATE $${idVar} SET ${keyDataVar.map((
|
|
55
|
+
return `UPDATE $${idVar} SET ${keyDataVar.map((kdv) => typeof kdv === "string" ? `${kdv} = $${kdv}` : "statement" in kdv ? kdv.statement : `${kdv.key} = $${kdv.variable}`).join(", ")}`;
|
|
52
56
|
},
|
|
53
57
|
delete(idVar) {
|
|
54
58
|
return `DELETE $${idVar}`;
|
|
@@ -76,7 +80,7 @@ const surql = {
|
|
|
76
80
|
//#region src/utils/parser.ts
|
|
77
81
|
function cleanRecord(tableSchema, record) {
|
|
78
82
|
const cleaned = {};
|
|
79
|
-
for (const [key, value] of Object.entries(record)) if (key === "id" || key in tableSchema) cleaned[key] = value;
|
|
83
|
+
for (const [key, value] of Object.entries(record)) if (key === "id" || key.startsWith("_00_") || key in tableSchema) cleaned[key] = value;
|
|
80
84
|
return cleaned;
|
|
81
85
|
}
|
|
82
86
|
function parseParams(tableSchema, params) {
|
|
@@ -148,12 +152,21 @@ function generateId() {
|
|
|
148
152
|
return Uuid.v4().toString().replace(/-/g, "");
|
|
149
153
|
}
|
|
150
154
|
/**
|
|
155
|
+
* Read the millisecond count off a surrealdb `Duration`. Different `surrealdb`
|
|
156
|
+
* releases expose it under `milliseconds` (current) or the older private
|
|
157
|
+
* `_milliseconds` field, so read whichever is set; returns 0 when neither is.
|
|
158
|
+
*/
|
|
159
|
+
function durationMillis(duration) {
|
|
160
|
+
const d = duration;
|
|
161
|
+
return Number(d.milliseconds || d._milliseconds || 0);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
151
164
|
* Parse duration string or Duration object to milliseconds
|
|
152
165
|
*/
|
|
153
166
|
function parseDuration(duration) {
|
|
154
167
|
if (duration instanceof Duration) {
|
|
155
|
-
const ms = duration
|
|
156
|
-
if (ms) return
|
|
168
|
+
const ms = durationMillis(duration);
|
|
169
|
+
if (ms) return ms;
|
|
157
170
|
const str = duration.toString();
|
|
158
171
|
if (str !== "[object Object]") return parseDuration(str);
|
|
159
172
|
return 6e5;
|
|
@@ -162,7 +175,7 @@ function parseDuration(duration) {
|
|
|
162
175
|
if (typeof duration !== "string") return 6e5;
|
|
163
176
|
const match = duration.match(/^(\d+)([smh])$/);
|
|
164
177
|
if (!match) return 6e5;
|
|
165
|
-
const val = parseInt(match[1], 10);
|
|
178
|
+
const val = Number.parseInt(match[1], 10);
|
|
166
179
|
switch (match[2]) {
|
|
167
180
|
case "s": return val * 1e3;
|
|
168
181
|
case "h": return val * 36e5;
|
|
@@ -174,6 +187,13 @@ async function fileToUint8Array(file) {
|
|
|
174
187
|
return new Uint8Array(buffer);
|
|
175
188
|
}
|
|
176
189
|
/**
|
|
190
|
+
* Convert plain text to simple HTML paragraphs.
|
|
191
|
+
* Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
|
|
192
|
+
*/
|
|
193
|
+
function textToHtml(text) {
|
|
194
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").split("\n").map((l) => `<p>${l || "<br>"}</p>`).join("");
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
177
197
|
* Helper for retrying DB operations with exponential backoff
|
|
178
198
|
*/
|
|
179
199
|
async function withRetry(logger, operation, retries = 3, delayMs = 100) {
|
|
@@ -188,7 +208,7 @@ async function withRetry(logger, operation, retries = 3, delayMs = 100) {
|
|
|
188
208
|
attempt: i + 1,
|
|
189
209
|
retries,
|
|
190
210
|
error: msg,
|
|
191
|
-
Category: "
|
|
211
|
+
Category: "sp00ky-client::utils::withRetry"
|
|
192
212
|
}, "Retrying DB operation");
|
|
193
213
|
await new Promise((res) => setTimeout(res, delayMs * (i + 1)));
|
|
194
214
|
continue;
|
|
@@ -198,8 +218,160 @@ async function withRetry(logger, operation, retries = 3, delayMs = 100) {
|
|
|
198
218
|
throw lastError;
|
|
199
219
|
}
|
|
200
220
|
|
|
221
|
+
//#endregion
|
|
222
|
+
//#region src/modules/data/window-query.ts
|
|
223
|
+
/**
|
|
224
|
+
* Rewrite a windowed (`LIMIT n START m`, m>0) SELECT so its rows are
|
|
225
|
+
* materialized from an explicit record-id set — the window the SSP already
|
|
226
|
+
* computed — instead of re-running the original query (with its `START m`)
|
|
227
|
+
* against the shared local DB.
|
|
228
|
+
*
|
|
229
|
+
* Why: `DataModule.processStreamUpdate` materializes a query's rows by
|
|
230
|
+
* re-querying the local in-browser SurrealDB with the original surql. For an
|
|
231
|
+
* offset query that re-applies `START m` against the *shared* local store —
|
|
232
|
+
* which, with sparse windowing, may hold only this window's rows — so it skips
|
|
233
|
+
* them all and returns nothing (the "page 2 returns 0 rows" bug). The SSP's
|
|
234
|
+
* materialized view (`StreamUpdate.localArray`) is exactly this window's row
|
|
235
|
+
* ids, so we select those ids directly and re-apply the original `ORDER BY` for
|
|
236
|
+
* stable display order.
|
|
237
|
+
*
|
|
238
|
+
* Returns `null` for non-offset queries (`START` absent or 0) — the caller
|
|
239
|
+
* keeps the normal re-query path, so only the broken case changes behavior.
|
|
240
|
+
*
|
|
241
|
+
* Preserves the `SELECT <projection>` clause and the top-level `ORDER BY`;
|
|
242
|
+
* drops the original `FROM`/`WHERE`/`LIMIT`/`START`. Subqueries inside the
|
|
243
|
+
* projection are preserved verbatim (the scanner is paren/quote aware), with
|
|
244
|
+
* one caveat: SurrealDB v3 drops `*` in the `SELECT *, <subquery> FROM $param`
|
|
245
|
+
* shape — such windowed+subquery queries are rare and were already returning 0,
|
|
246
|
+
* so this is no regression.
|
|
247
|
+
*/
|
|
248
|
+
function buildWindowMaterialization(surql, idsParam = "__win") {
|
|
249
|
+
const kw = scanTopLevelClauses(surql);
|
|
250
|
+
if (kw.startValue === null || kw.startValue <= 0) return null;
|
|
251
|
+
if (kw.fromIndex === null) return null;
|
|
252
|
+
const selectClause = surql.slice(0, kw.fromIndex).trimEnd();
|
|
253
|
+
let orderBy = "";
|
|
254
|
+
if (kw.orderByIndex !== null) {
|
|
255
|
+
const ends = [
|
|
256
|
+
kw.limitIndex,
|
|
257
|
+
kw.startIndex,
|
|
258
|
+
kw.semicolonIndex,
|
|
259
|
+
surql.length
|
|
260
|
+
].filter((n) => n !== null && n > kw.orderByIndex);
|
|
261
|
+
const end = Math.min(...ends);
|
|
262
|
+
orderBy = " " + surql.slice(kw.orderByIndex, end).trim();
|
|
263
|
+
}
|
|
264
|
+
return { query: `${selectClause} FROM $${idsParam}${orderBy}` };
|
|
265
|
+
}
|
|
266
|
+
function scanTopLevelClauses(sql) {
|
|
267
|
+
const out = {
|
|
268
|
+
fromIndex: null,
|
|
269
|
+
orderByIndex: null,
|
|
270
|
+
limitIndex: null,
|
|
271
|
+
startIndex: null,
|
|
272
|
+
startValue: null,
|
|
273
|
+
semicolonIndex: null
|
|
274
|
+
};
|
|
275
|
+
let depth = 0;
|
|
276
|
+
let inStr = false;
|
|
277
|
+
for (let i = 0; i < sql.length; i++) {
|
|
278
|
+
const ch = sql[i];
|
|
279
|
+
if (inStr) {
|
|
280
|
+
if (ch === "\\") i++;
|
|
281
|
+
else if (ch === "'") inStr = false;
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (ch === "'") {
|
|
285
|
+
inStr = true;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (ch === "(") {
|
|
289
|
+
depth++;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (ch === ")") {
|
|
293
|
+
depth--;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (depth !== 0) continue;
|
|
297
|
+
if (ch === ";" && out.semicolonIndex === null) {
|
|
298
|
+
out.semicolonIndex = i;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
if (!isWordBoundary(sql, i)) continue;
|
|
302
|
+
if (out.fromIndex === null && matchKeyword(sql, i, "FROM")) {
|
|
303
|
+
out.fromIndex = i;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
if (out.fromIndex === null) continue;
|
|
307
|
+
if (out.orderByIndex === null && matchKeyword(sql, i, "ORDER BY")) {
|
|
308
|
+
out.orderByIndex = i;
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (out.limitIndex === null && matchKeyword(sql, i, "LIMIT")) {
|
|
312
|
+
out.limitIndex = i;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (out.startIndex === null && matchKeyword(sql, i, "START")) {
|
|
316
|
+
out.startIndex = i;
|
|
317
|
+
out.startValue = readNumberAfter(sql, i + 5);
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
function isWordBoundary(sql, i) {
|
|
324
|
+
if (i === 0) return true;
|
|
325
|
+
return !/[A-Za-z0-9_]/.test(sql[i - 1]);
|
|
326
|
+
}
|
|
327
|
+
function matchKeyword(sql, i, keyword) {
|
|
328
|
+
const parts = keyword.split(" ");
|
|
329
|
+
let pos = i;
|
|
330
|
+
for (let p = 0; p < parts.length; p++) {
|
|
331
|
+
const word = parts[p];
|
|
332
|
+
if (sql.slice(pos, pos + word.length).toUpperCase() !== word) return false;
|
|
333
|
+
pos += word.length;
|
|
334
|
+
if (p < parts.length - 1) {
|
|
335
|
+
const wsStart = pos;
|
|
336
|
+
while (pos < sql.length && /\s/.test(sql[pos])) pos++;
|
|
337
|
+
if (pos === wsStart) return false;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return pos >= sql.length || !/[A-Za-z0-9_]/.test(sql[pos]);
|
|
341
|
+
}
|
|
342
|
+
function readNumberAfter(sql, from) {
|
|
343
|
+
let pos = from;
|
|
344
|
+
while (pos < sql.length && /\s/.test(sql[pos])) pos++;
|
|
345
|
+
const m = /^\d+/.exec(sql.slice(pos));
|
|
346
|
+
return m ? parseInt(m[0], 10) : null;
|
|
347
|
+
}
|
|
348
|
+
|
|
201
349
|
//#endregion
|
|
202
350
|
//#region src/modules/data/index.ts
|
|
351
|
+
/** Push a timing sample (ms) into a rolling window, capped at the sample window. */
|
|
352
|
+
function pushSample(samples, ms) {
|
|
353
|
+
samples.push(ms);
|
|
354
|
+
if (samples.length > MATERIALIZATION_SAMPLE_WINDOW) samples.shift();
|
|
355
|
+
}
|
|
356
|
+
/** Build a {lastMs,p50,p90,p99,count} summary from a rolling sample window. */
|
|
357
|
+
function phaseStatOf(samples, lastMs) {
|
|
358
|
+
if (samples.length === 0) return {
|
|
359
|
+
lastMs,
|
|
360
|
+
p50: null,
|
|
361
|
+
p90: null,
|
|
362
|
+
p99: null,
|
|
363
|
+
count: 0
|
|
364
|
+
};
|
|
365
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
366
|
+
const pick = (q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
|
|
367
|
+
return {
|
|
368
|
+
lastMs,
|
|
369
|
+
p50: pick(.5),
|
|
370
|
+
p90: pick(.9),
|
|
371
|
+
p99: pick(.99),
|
|
372
|
+
count: samples.length
|
|
373
|
+
};
|
|
374
|
+
}
|
|
203
375
|
/**
|
|
204
376
|
* DataModule - Unified query and mutation management
|
|
205
377
|
*
|
|
@@ -210,9 +382,38 @@ var DataModule = class {
|
|
|
210
382
|
activeQueries = /* @__PURE__ */ new Map();
|
|
211
383
|
pendingQueries = /* @__PURE__ */ new Map();
|
|
212
384
|
subscriptions = /* @__PURE__ */ new Map();
|
|
385
|
+
statusSubscriptions = /* @__PURE__ */ new Map();
|
|
213
386
|
mutationCallbacks = /* @__PURE__ */ new Set();
|
|
214
387
|
debounceTimers = /* @__PURE__ */ new Map();
|
|
215
388
|
logger;
|
|
389
|
+
/**
|
|
390
|
+
* Optional observer notified whenever a query's fetch status changes.
|
|
391
|
+
* Wired by Sp00kyClient to push status changes into DevTools. Kept as a
|
|
392
|
+
* settable field (rather than a constructor arg) because DevTools is
|
|
393
|
+
* constructed after DataModule.
|
|
394
|
+
*/
|
|
395
|
+
onQueryStatusChange;
|
|
396
|
+
/**
|
|
397
|
+
* Optional observer invoked when a still-subscribed query's TTL heartbeat
|
|
398
|
+
* fires (~90% of the TTL). Wired by Sp00kyClient to
|
|
399
|
+
* `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
|
|
400
|
+
* row's `lastActiveAt` so an actively-watched query never expires. Settable
|
|
401
|
+
* field (not a constructor arg) because the sync engine is wired after
|
|
402
|
+
* DataModule is constructed — mirrors `onQueryStatusChange`.
|
|
403
|
+
*/
|
|
404
|
+
onHeartbeat;
|
|
405
|
+
/**
|
|
406
|
+
* Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
|
|
407
|
+
* viewport-windowed list cancelling an off-screen window) loses its last
|
|
408
|
+
* subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
|
|
409
|
+
* tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
|
|
410
|
+
* instead of leaving it for the TTL sweep. The local view + state are freed in
|
|
411
|
+
* {@link finalizeDeregister} only after that remote delete, so a fast
|
|
412
|
+
* re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
|
|
413
|
+
*/
|
|
414
|
+
onDeregister;
|
|
415
|
+
sessionId = "";
|
|
416
|
+
currentUserId = null;
|
|
216
417
|
constructor(cache, local, schema, logger, streamDebounceTime = 100) {
|
|
217
418
|
this.cache = cache;
|
|
218
419
|
this.local = local;
|
|
@@ -220,8 +421,35 @@ var DataModule = class {
|
|
|
220
421
|
this.streamDebounceTime = streamDebounceTime;
|
|
221
422
|
this.logger = logger.child({ service: "DataModule" });
|
|
222
423
|
}
|
|
223
|
-
async init() {
|
|
224
|
-
this.
|
|
424
|
+
async init(sessionId) {
|
|
425
|
+
this.sessionId = sessionId;
|
|
426
|
+
this.logger.info({
|
|
427
|
+
sessionId,
|
|
428
|
+
Category: "sp00ky-client::DataModule::init"
|
|
429
|
+
}, "DataModule initialized");
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Update the session salt used in query-id hashing. Call this when the
|
|
433
|
+
* SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
|
|
434
|
+
* registered queries will get fresh, session-scoped IDs.
|
|
435
|
+
*/
|
|
436
|
+
setSessionId(sessionId) {
|
|
437
|
+
this.sessionId = sessionId;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Update the authenticated user record id. Pass `null` on sign-out.
|
|
441
|
+
* Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
|
|
442
|
+
* the poll route to the same per-user `_00_list_ref_user_<id>` the
|
|
443
|
+
* SSP writes to.
|
|
444
|
+
*/
|
|
445
|
+
setCurrentUserId(userId) {
|
|
446
|
+
this.currentUserId = userId;
|
|
447
|
+
}
|
|
448
|
+
/** Read-only view of the authenticated user id used for per-user
|
|
449
|
+
* `_00_list_ref` routing. Other modules consult this so they pick the
|
|
450
|
+
* same table name DataModule does. */
|
|
451
|
+
getCurrentUserId() {
|
|
452
|
+
return this.currentUserId;
|
|
225
453
|
}
|
|
226
454
|
/**
|
|
227
455
|
* Register a query and return its hash for subscriptions
|
|
@@ -233,27 +461,27 @@ var DataModule = class {
|
|
|
233
461
|
});
|
|
234
462
|
this.logger.debug({
|
|
235
463
|
hash,
|
|
236
|
-
Category: "
|
|
464
|
+
Category: "sp00ky-client::DataModule::query"
|
|
237
465
|
}, "Query Initialization: started");
|
|
238
|
-
const recordId = new RecordId("
|
|
466
|
+
const recordId = new RecordId("_00_query", hash);
|
|
239
467
|
if (this.activeQueries.has(hash)) {
|
|
240
468
|
this.logger.debug({
|
|
241
469
|
hash,
|
|
242
|
-
Category: "
|
|
470
|
+
Category: "sp00ky-client::DataModule::query"
|
|
243
471
|
}, "Query Initialization: exists, returning");
|
|
244
472
|
return hash;
|
|
245
473
|
}
|
|
246
474
|
if (this.pendingQueries.has(hash)) {
|
|
247
475
|
this.logger.debug({
|
|
248
476
|
hash,
|
|
249
|
-
Category: "
|
|
477
|
+
Category: "sp00ky-client::DataModule::query"
|
|
250
478
|
}, "Query Initialization: pending, waiting for existing creation");
|
|
251
479
|
await this.pendingQueries.get(hash);
|
|
252
480
|
return hash;
|
|
253
481
|
}
|
|
254
482
|
this.logger.debug({
|
|
255
483
|
hash,
|
|
256
|
-
Category: "
|
|
484
|
+
Category: "sp00ky-client::DataModule::query"
|
|
257
485
|
}, "Query Initialization: not found, creating new query");
|
|
258
486
|
const promise = this.createAndRegisterQuery(hash, recordId, surqlString, params, ttl, tableName);
|
|
259
487
|
this.pendingQueries.set(hash, promise);
|
|
@@ -283,6 +511,36 @@ var DataModule = class {
|
|
|
283
511
|
};
|
|
284
512
|
}
|
|
285
513
|
/**
|
|
514
|
+
* Subscribe to a query's fetch-status changes (idle/fetching).
|
|
515
|
+
* With `{ immediate: true }` the callback fires synchronously with the
|
|
516
|
+
* current status (defaults to `idle` if the query isn't registered yet).
|
|
517
|
+
*/
|
|
518
|
+
subscribeStatus(queryHash, callback, options = {}) {
|
|
519
|
+
if (!this.statusSubscriptions.has(queryHash)) this.statusSubscriptions.set(queryHash, /* @__PURE__ */ new Set());
|
|
520
|
+
this.statusSubscriptions.get(queryHash)?.add(callback);
|
|
521
|
+
if (options.immediate) callback(this.activeQueries.get(queryHash)?.status ?? "idle");
|
|
522
|
+
return () => {
|
|
523
|
+
const subs = this.statusSubscriptions.get(queryHash);
|
|
524
|
+
if (subs) {
|
|
525
|
+
subs.delete(callback);
|
|
526
|
+
if (subs.size === 0) this.statusSubscriptions.delete(queryHash);
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Set a query's fetch status and notify status observers (DevTools +
|
|
532
|
+
* `subscribeStatus` listeners). No-op when the status is unchanged or the
|
|
533
|
+
* query is unknown.
|
|
534
|
+
*/
|
|
535
|
+
setQueryStatus(queryHash, status) {
|
|
536
|
+
const queryState = this.activeQueries.get(queryHash);
|
|
537
|
+
if (!queryState || queryState.status === status) return;
|
|
538
|
+
queryState.status = status;
|
|
539
|
+
this.onQueryStatusChange?.(queryHash, status);
|
|
540
|
+
const subs = this.statusSubscriptions.get(queryHash);
|
|
541
|
+
if (subs) for (const callback of subs) callback(status);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
286
544
|
* Subscribe to mutations (for sync)
|
|
287
545
|
*/
|
|
288
546
|
onMutation(callback) {
|
|
@@ -296,66 +554,298 @@ var DataModule = class {
|
|
|
296
554
|
*/
|
|
297
555
|
async onStreamUpdate(update) {
|
|
298
556
|
const { queryHash, op } = update;
|
|
299
|
-
if (op === "
|
|
300
|
-
|
|
301
|
-
|
|
557
|
+
if (op === "DELETE") {
|
|
558
|
+
const existing = this.debounceTimers.get(queryHash);
|
|
559
|
+
if (existing) {
|
|
560
|
+
clearTimeout(existing);
|
|
302
561
|
this.debounceTimers.delete(queryHash);
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
}
|
|
562
|
+
}
|
|
563
|
+
await this.processStreamUpdate(update);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (this.debounceTimers.has(queryHash)) clearTimeout(this.debounceTimers.get(queryHash));
|
|
567
|
+
const timer = setTimeout(async () => {
|
|
568
|
+
this.debounceTimers.delete(queryHash);
|
|
569
|
+
await this.processStreamUpdate(update);
|
|
570
|
+
}, this.streamDebounceTime);
|
|
571
|
+
this.debounceTimers.set(queryHash, timer);
|
|
572
|
+
}
|
|
573
|
+
async materializeRecords(queryState, sspArray) {
|
|
574
|
+
const t0 = performance.now();
|
|
575
|
+
const windowMat = buildWindowMaterialization(queryState.config.surql);
|
|
576
|
+
let records;
|
|
577
|
+
if (windowMat) {
|
|
578
|
+
const winIds = (queryState.config.remoteArray?.length && queryState.config.remoteArray || sspArray?.length && sspArray || queryState.config.localArray || []).map(([id]) => parseRecordIdString(id));
|
|
579
|
+
const [rows] = await this.local.query(windowMat.query, {
|
|
580
|
+
...queryState.config.params,
|
|
581
|
+
__win: winIds
|
|
582
|
+
});
|
|
583
|
+
records = rows || [];
|
|
584
|
+
} else {
|
|
585
|
+
const [rows] = await this.local.query(queryState.config.surql, queryState.config.params);
|
|
586
|
+
records = rows || [];
|
|
587
|
+
}
|
|
588
|
+
this.recordPhase(queryState, "localFetch", performance.now() - t0);
|
|
589
|
+
return records;
|
|
307
590
|
}
|
|
308
591
|
async processStreamUpdate(update) {
|
|
309
|
-
const { queryHash, localArray } = update;
|
|
592
|
+
const { queryHash, localArray, materializationTimeMs } = update;
|
|
310
593
|
const queryState = this.activeQueries.get(queryHash);
|
|
311
594
|
if (!queryState) {
|
|
312
595
|
this.logger.warn({
|
|
313
596
|
queryHash,
|
|
314
|
-
Category: "
|
|
597
|
+
Category: "sp00ky-client::DataModule::onStreamUpdate"
|
|
315
598
|
}, "Received update for unknown query. Skipping...");
|
|
316
599
|
return;
|
|
317
600
|
}
|
|
601
|
+
if (typeof materializationTimeMs === "number") {
|
|
602
|
+
queryState.materializationSamples.push(materializationTimeMs);
|
|
603
|
+
if (queryState.materializationSamples.length > MATERIALIZATION_SAMPLE_WINDOW) queryState.materializationSamples.shift();
|
|
604
|
+
queryState.lastIngestLatencyMs = materializationTimeMs;
|
|
605
|
+
}
|
|
606
|
+
if (typeof update.storeApplyMs === "number") this.recordPhase(queryState, "sspStoreApply", update.storeApplyMs);
|
|
607
|
+
if (typeof update.circuitStepMs === "number") this.recordPhase(queryState, "sspCircuitStep", update.circuitStepMs);
|
|
608
|
+
if (typeof update.transformMs === "number") this.recordPhase(queryState, "sspTransform", update.transformMs);
|
|
609
|
+
const percentiles = this.computeMaterializationPercentiles(queryState.materializationSamples);
|
|
318
610
|
try {
|
|
319
|
-
const
|
|
320
|
-
const newRecords = records || [];
|
|
611
|
+
const newRecords = await this.materializeRecords(queryState, localArray);
|
|
321
612
|
queryState.config.localArray = localArray;
|
|
322
|
-
await this.local.query(surql.seal(surql.updateSet("id", ["localArray"])), {
|
|
323
|
-
id: queryState.config.id,
|
|
324
|
-
localArray
|
|
325
|
-
});
|
|
326
613
|
const prevJson = JSON.stringify(queryState.records);
|
|
327
614
|
const newJson = JSON.stringify(newRecords);
|
|
328
615
|
queryState.records = newRecords;
|
|
329
|
-
|
|
616
|
+
const recordsChanged = prevJson !== newJson;
|
|
617
|
+
if (recordsChanged) queryState.updateCount++;
|
|
618
|
+
await this.local.query(surql.seal(surql.updateSet("id", [
|
|
619
|
+
"localArray",
|
|
620
|
+
"rowCount",
|
|
621
|
+
"updateCount",
|
|
622
|
+
"lastIngestLatency",
|
|
623
|
+
"materializationP55",
|
|
624
|
+
"materializationP90",
|
|
625
|
+
"materializationP99"
|
|
626
|
+
])), {
|
|
627
|
+
id: queryState.config.id,
|
|
628
|
+
localArray,
|
|
629
|
+
rowCount: localArray.length,
|
|
630
|
+
updateCount: queryState.updateCount,
|
|
631
|
+
lastIngestLatency: queryState.lastIngestLatencyMs,
|
|
632
|
+
materializationP55: percentiles.p55,
|
|
633
|
+
materializationP90: percentiles.p90,
|
|
634
|
+
materializationP99: percentiles.p99
|
|
635
|
+
});
|
|
636
|
+
if (!recordsChanged) {
|
|
330
637
|
this.logger.debug({
|
|
331
638
|
queryHash,
|
|
332
|
-
Category: "
|
|
639
|
+
Category: "sp00ky-client::DataModule::onStreamUpdate"
|
|
333
640
|
}, "Query records unchanged, skipping notification");
|
|
334
641
|
return;
|
|
335
642
|
}
|
|
336
|
-
queryState.updateCount++;
|
|
337
643
|
const subscribers = this.subscriptions.get(queryHash);
|
|
338
644
|
if (subscribers) for (const callback of subscribers) callback(queryState.records);
|
|
339
645
|
this.logger.debug({
|
|
340
646
|
queryHash,
|
|
341
|
-
recordCount:
|
|
342
|
-
Category: "
|
|
647
|
+
recordCount: newRecords?.length,
|
|
648
|
+
Category: "sp00ky-client::DataModule::onStreamUpdate"
|
|
343
649
|
}, "Query updated from stream");
|
|
344
650
|
} catch (err) {
|
|
651
|
+
queryState.errorCount++;
|
|
345
652
|
this.logger.error({
|
|
346
653
|
err,
|
|
347
654
|
queryHash,
|
|
348
|
-
Category: "
|
|
655
|
+
Category: "sp00ky-client::DataModule::onStreamUpdate"
|
|
349
656
|
}, "Failed to fetch records for stream update");
|
|
657
|
+
try {
|
|
658
|
+
await this.local.query(surql.seal(surql.updateSet("id", ["errorCount"])), {
|
|
659
|
+
id: queryState.config.id,
|
|
660
|
+
errorCount: queryState.errorCount
|
|
661
|
+
});
|
|
662
|
+
} catch (persistErr) {
|
|
663
|
+
this.logger.warn({
|
|
664
|
+
err: persistErr,
|
|
665
|
+
queryHash,
|
|
666
|
+
Category: "sp00ky-client::DataModule::onStreamUpdate"
|
|
667
|
+
}, "Failed to persist incremented errorCount");
|
|
668
|
+
}
|
|
350
669
|
}
|
|
351
670
|
}
|
|
352
671
|
/**
|
|
672
|
+
* Compute p55/p90/p99 from a rolling window of materialization samples.
|
|
673
|
+
* Returns nulls for any percentile that has no samples yet so SurrealDB
|
|
674
|
+
* `option<float>` columns stay NONE rather than 0 before the first ingest.
|
|
675
|
+
*/
|
|
676
|
+
computeMaterializationPercentiles(samples) {
|
|
677
|
+
if (samples.length === 0) return {
|
|
678
|
+
p55: null,
|
|
679
|
+
p90: null,
|
|
680
|
+
p99: null
|
|
681
|
+
};
|
|
682
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
683
|
+
const pick = (q) => {
|
|
684
|
+
return sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
|
|
685
|
+
};
|
|
686
|
+
return {
|
|
687
|
+
p55: pick(.55),
|
|
688
|
+
p90: pick(.9),
|
|
689
|
+
p99: pick(.99)
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
/** Record a per-phase timing sample (ms) on a query's rolling window. */
|
|
693
|
+
recordPhase(qs, phase, ms) {
|
|
694
|
+
if (!Number.isFinite(ms)) return;
|
|
695
|
+
pushSample(qs.phaseSamples[phase] ?? (qs.phaseSamples[phase] = []), ms);
|
|
696
|
+
qs.phaseLast[phase] = ms;
|
|
697
|
+
}
|
|
698
|
+
/** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
|
|
699
|
+
recordRemoteFetch(hash, ms) {
|
|
700
|
+
const qs = this.activeQueries.get(hash);
|
|
701
|
+
if (qs) this.recordPhase(qs, "remoteFetch", ms);
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Record the frontend reconcile time (ms) for a query. Called from `useQuery`
|
|
705
|
+
* via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
|
|
706
|
+
*/
|
|
707
|
+
recordFrontendTiming(hash, ms) {
|
|
708
|
+
const qs = this.activeQueries.get(hash);
|
|
709
|
+
if (qs) this.recordPhase(qs, "frontend", ms);
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Build the per-query processing-time breakdown surfaced to the DevTools panel
|
|
713
|
+
* and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
|
|
714
|
+
* the rest come from the per-phase rolling windows + one-shot registration timings.
|
|
715
|
+
*/
|
|
716
|
+
phaseTimings(q) {
|
|
717
|
+
const stat = (phase) => phaseStatOf(q.phaseSamples[phase] ?? [], q.phaseLast[phase] ?? null);
|
|
718
|
+
return {
|
|
719
|
+
ssp: phaseStatOf(q.materializationSamples, q.lastIngestLatencyMs),
|
|
720
|
+
sspStoreApply: stat("sspStoreApply"),
|
|
721
|
+
sspCircuitStep: stat("sspCircuitStep"),
|
|
722
|
+
sspTransform: stat("sspTransform"),
|
|
723
|
+
localFetch: stat("localFetch"),
|
|
724
|
+
remoteFetch: stat("remoteFetch"),
|
|
725
|
+
frontend: stat("frontend"),
|
|
726
|
+
registration: q.registrationTimings,
|
|
727
|
+
updateCount: q.updateCount,
|
|
728
|
+
errorCount: q.errorCount
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
353
732
|
* Get query state (for sync and devtools)
|
|
354
733
|
*/
|
|
355
734
|
getQueryByHash(hash) {
|
|
356
735
|
return this.activeQueries.get(hash);
|
|
357
736
|
}
|
|
358
737
|
/**
|
|
738
|
+
* Cold-query guard for instant-hydrate: true when the query exists, hasn't been
|
|
739
|
+
* hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
|
|
740
|
+
* We gate on `remoteArray`, not local `records`: a windowed query is often
|
|
741
|
+
* partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
|
|
742
|
+
* but it still hasn't loaded its own full window from the server — so it should
|
|
743
|
+
* still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
|
|
744
|
+
*/
|
|
745
|
+
isCold(hash) {
|
|
746
|
+
const qs = this.activeQueries.get(hash);
|
|
747
|
+
return !!qs && !qs.hydrated && (qs.config.remoteArray?.length ?? 0) === 0;
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Walk a hydrated record's fields and append any EMBEDDED child records to
|
|
751
|
+
* `batch` (recursing for nested related fields). An embedded child is a
|
|
752
|
+
* value that is itself a record — a non-null object whose `id` is a
|
|
753
|
+
* `RecordId` — or an array of such records (one-to-many vs one-to-one). A
|
|
754
|
+
* bare `RecordId` (a foreign-key reference) or any other value is skipped,
|
|
755
|
+
* so this never mistakes a FK column for an embedded body. Children are
|
|
756
|
+
* keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
|
|
757
|
+
* to their table's real columns (which strips the alias/related fields).
|
|
758
|
+
* `seen` dedupes within the batch.
|
|
759
|
+
*/
|
|
760
|
+
collectEmbeddedChildren(record, batch, seen) {
|
|
761
|
+
const isEmbeddedRecord = (v) => !!v && typeof v === "object" && !(v instanceof RecordId) && v.id instanceof RecordId;
|
|
762
|
+
for (const value of Object.values(record)) {
|
|
763
|
+
const children = Array.isArray(value) ? value.filter(isEmbeddedRecord) : isEmbeddedRecord(value) ? [value] : [];
|
|
764
|
+
for (const child of children) {
|
|
765
|
+
const key = encodeRecordId(child.id);
|
|
766
|
+
if (seen.has(key)) continue;
|
|
767
|
+
seen.add(key);
|
|
768
|
+
this.collectEmbeddedChildren(child, batch, seen);
|
|
769
|
+
const table = child.id.table.toString();
|
|
770
|
+
const tableSchema = this.schema.tables.find((t) => t.name === table);
|
|
771
|
+
batch.push({
|
|
772
|
+
table,
|
|
773
|
+
op: "CREATE",
|
|
774
|
+
record: tableSchema ? cleanRecord(tableSchema.columns, child) : child,
|
|
775
|
+
version: child._00_rv || 1
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
|
|
782
|
+
* surql run directly) so the query DISPLAYS immediately, while the full realtime
|
|
783
|
+
* registration proceeds in the background. Ingests with versions (`_00_rv`) so the
|
|
784
|
+
* later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
|
|
785
|
+
* `remoteArray` so windowed queries materialize the correct window (no sparse
|
|
786
|
+
* local-circuit issue). Runs at most once per query (the `hydrated` flag).
|
|
787
|
+
*/
|
|
788
|
+
async applyHydration(hash, rows) {
|
|
789
|
+
const queryState = this.activeQueries.get(hash);
|
|
790
|
+
if (!queryState) return;
|
|
791
|
+
queryState.hydrated = true;
|
|
792
|
+
if (rows.length === 0) return;
|
|
793
|
+
const tableName = queryState.config.tableName;
|
|
794
|
+
const batch = rows.map((record) => ({
|
|
795
|
+
table: tableName,
|
|
796
|
+
op: "CREATE",
|
|
797
|
+
record,
|
|
798
|
+
version: record._00_rv || 1
|
|
799
|
+
}));
|
|
800
|
+
const seen = new Set(rows.map((r) => encodeRecordId(r.id)));
|
|
801
|
+
for (const record of rows) this.collectEmbeddedChildren(record, batch, seen);
|
|
802
|
+
await this.cache.saveBatch(batch);
|
|
803
|
+
queryState.config.remoteArray = rows.map((r) => [encodeRecordId(r.id), r._00_rv || 1]);
|
|
804
|
+
queryState.records = await this.materializeRecords(queryState);
|
|
805
|
+
const subscribers = this.subscriptions.get(hash);
|
|
806
|
+
if (subscribers) for (const cb of subscribers) cb(queryState.records);
|
|
807
|
+
}
|
|
808
|
+
/** True while ≥1 live subscriber is watching this query (refcount guard). */
|
|
809
|
+
hasSubscribers(hash) {
|
|
810
|
+
return (this.subscriptions.get(hash)?.size ?? 0) > 0;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Opt-in eager teardown for a query whose LAST subscriber just left — used by
|
|
814
|
+
* viewport-windowed lists to cancel off-screen windows instead of leaving
|
|
815
|
+
* their remote views to expire on the TTL sweep. No-op while any subscriber
|
|
816
|
+
* remains (refcount). Only enqueues the remote cleanup here; the local WASM
|
|
817
|
+
* view + in-memory state are freed in {@link finalizeDeregister} after the
|
|
818
|
+
* remote delete completes, so a re-subscribe in between aborts/heals it.
|
|
819
|
+
*
|
|
820
|
+
* NOTE: most queries should NOT use this — the default keep-alive on
|
|
821
|
+
* unsubscribe avoids re-registration churn on navigation.
|
|
822
|
+
*/
|
|
823
|
+
deregisterQuery(hash) {
|
|
824
|
+
if (this.hasSubscribers(hash)) return;
|
|
825
|
+
if (!this.activeQueries.has(hash)) return;
|
|
826
|
+
this.onDeregister?.(hash);
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Final local teardown after the remote `_00_query` row was deleted: free the
|
|
830
|
+
* WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
|
|
831
|
+
* (`cleanupQuery`) guarantees no subscriber remains.
|
|
832
|
+
*/
|
|
833
|
+
finalizeDeregister(hash) {
|
|
834
|
+
const qs = this.activeQueries.get(hash);
|
|
835
|
+
if (qs?.ttlTimer) {
|
|
836
|
+
clearTimeout(qs.ttlTimer);
|
|
837
|
+
qs.ttlTimer = null;
|
|
838
|
+
}
|
|
839
|
+
const debounce = this.debounceTimers.get(hash);
|
|
840
|
+
if (debounce) {
|
|
841
|
+
clearTimeout(debounce);
|
|
842
|
+
this.debounceTimers.delete(hash);
|
|
843
|
+
}
|
|
844
|
+
this.cache.unregisterQuery(hash);
|
|
845
|
+
this.activeQueries.delete(hash);
|
|
846
|
+
this.subscriptions.delete(hash);
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
359
849
|
* Get query state by id (for sync and devtools)
|
|
360
850
|
*/
|
|
361
851
|
getQueryById(id) {
|
|
@@ -367,12 +857,15 @@ var DataModule = class {
|
|
|
367
857
|
getActiveQueries() {
|
|
368
858
|
return Array.from(this.activeQueries.values());
|
|
369
859
|
}
|
|
860
|
+
getActiveQueryHashes() {
|
|
861
|
+
return Array.from(this.activeQueries.keys());
|
|
862
|
+
}
|
|
370
863
|
async updateQueryLocalArray(id, localArray) {
|
|
371
864
|
const queryState = this.activeQueries.get(id);
|
|
372
865
|
if (!queryState) {
|
|
373
866
|
this.logger.warn({
|
|
374
867
|
id,
|
|
375
|
-
Category: "
|
|
868
|
+
Category: "sp00ky-client::DataModule::updateQueryLocalArray"
|
|
376
869
|
}, "Query to update local array not found");
|
|
377
870
|
return;
|
|
378
871
|
}
|
|
@@ -387,7 +880,7 @@ var DataModule = class {
|
|
|
387
880
|
if (!queryState) {
|
|
388
881
|
this.logger.warn({
|
|
389
882
|
hash,
|
|
390
|
-
Category: "
|
|
883
|
+
Category: "sp00ky-client::DataModule::updateQueryRemoteArray"
|
|
391
884
|
}, "Query to update remote array not found");
|
|
392
885
|
return;
|
|
393
886
|
}
|
|
@@ -404,8 +897,7 @@ var DataModule = class {
|
|
|
404
897
|
async notifyQuerySynced(queryHash) {
|
|
405
898
|
const queryState = this.activeQueries.get(queryHash);
|
|
406
899
|
if (!queryState) return;
|
|
407
|
-
const
|
|
408
|
-
const newRecords = records || [];
|
|
900
|
+
const newRecords = await this.materializeRecords(queryState);
|
|
409
901
|
const changed = JSON.stringify(queryState.records) !== JSON.stringify(newRecords);
|
|
410
902
|
queryState.records = newRecords;
|
|
411
903
|
if (changed || queryState.updateCount === 0) {
|
|
@@ -431,6 +923,7 @@ var DataModule = class {
|
|
|
431
923
|
max_retries: options?.max_retries ?? 3,
|
|
432
924
|
retry_strategy: options?.retry_strategy ?? "linear"
|
|
433
925
|
};
|
|
926
|
+
if (options?.timeout != null) record.timeout = options.timeout;
|
|
434
927
|
if (options?.assignedTo) record.assigned_to = options.assignedTo;
|
|
435
928
|
const recordId = `${tableName}:${generateId()}`;
|
|
436
929
|
await this.create(recordId, record);
|
|
@@ -444,7 +937,7 @@ var DataModule = class {
|
|
|
444
937
|
if (!tableSchema) throw new Error(`Table ${tableName} not found`);
|
|
445
938
|
const rid = parseRecordIdString(id);
|
|
446
939
|
const params = parseParams(tableSchema.columns, data);
|
|
447
|
-
const mutationId = parseRecordIdString(`
|
|
940
|
+
const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
|
|
448
941
|
const dataKeys = Object.keys(params).map((key) => ({
|
|
449
942
|
key,
|
|
450
943
|
variable: `data_${key}`
|
|
@@ -474,7 +967,7 @@ var DataModule = class {
|
|
|
474
967
|
for (const callback of this.mutationCallbacks) callback([mutationEvent]);
|
|
475
968
|
this.logger.debug({
|
|
476
969
|
id,
|
|
477
|
-
Category: "
|
|
970
|
+
Category: "sp00ky-client::DataModule::create"
|
|
478
971
|
}, "Record created");
|
|
479
972
|
return target;
|
|
480
973
|
}
|
|
@@ -487,10 +980,10 @@ var DataModule = class {
|
|
|
487
980
|
if (!tableSchema) throw new Error(`Table ${tableName} not found`);
|
|
488
981
|
const rid = parseRecordIdString(id);
|
|
489
982
|
const params = parseParams(tableSchema.columns, data);
|
|
490
|
-
const mutationId = parseRecordIdString(`
|
|
983
|
+
const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
|
|
491
984
|
const [beforeRecord] = await withRetry(this.logger, () => this.local.query("SELECT * FROM ONLY $id", { id: rid }));
|
|
492
985
|
const query = surql.seal(surql.tx([
|
|
493
|
-
surql.updateSet("id", [{ statement: "
|
|
986
|
+
surql.updateSet("id", [{ statement: "_00_rv += 1" }]),
|
|
494
987
|
surql.let("updated", surql.updateMerge("id", "data")),
|
|
495
988
|
surql.createMutation("update", "mid", "id", "data"),
|
|
496
989
|
surql.returnObject([{
|
|
@@ -505,14 +998,14 @@ var DataModule = class {
|
|
|
505
998
|
}));
|
|
506
999
|
const updatedFields = { id: target.id };
|
|
507
1000
|
for (const key of Object.keys(data)) if (key in target) updatedFields[key] = target[key];
|
|
508
|
-
if ("
|
|
1001
|
+
if ("_00_rv" in target) updatedFields._00_rv = target._00_rv;
|
|
509
1002
|
this.replaceRecordInQueries(updatedFields);
|
|
510
1003
|
const parsedRecord = parseParams(tableSchema.columns, target);
|
|
511
1004
|
await this.cache.save({
|
|
512
1005
|
table,
|
|
513
1006
|
op: "UPDATE",
|
|
514
1007
|
record: parsedRecord,
|
|
515
|
-
version: target.
|
|
1008
|
+
version: target._00_rv
|
|
516
1009
|
}, true);
|
|
517
1010
|
const pushEventOptions = parseUpdateOptions(id, data, options);
|
|
518
1011
|
const mutationEvent = {
|
|
@@ -527,7 +1020,7 @@ var DataModule = class {
|
|
|
527
1020
|
for (const callback of this.mutationCallbacks) callback([mutationEvent]);
|
|
528
1021
|
this.logger.debug({
|
|
529
1022
|
id,
|
|
530
|
-
Category: "
|
|
1023
|
+
Category: "sp00ky-client::DataModule::update"
|
|
531
1024
|
}, "Record updated");
|
|
532
1025
|
return target;
|
|
533
1026
|
}
|
|
@@ -538,13 +1031,32 @@ var DataModule = class {
|
|
|
538
1031
|
const tableName = extractTablePart(id);
|
|
539
1032
|
if (!this.schema.tables.find((t) => t.name === tableName)) throw new Error(`Table ${tableName} not found`);
|
|
540
1033
|
const rid = parseRecordIdString(id);
|
|
541
|
-
const mutationId = parseRecordIdString(`
|
|
1034
|
+
const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
|
|
1035
|
+
const [beforeRecords] = await this.local.query("SELECT * FROM ONLY $id", { id: rid });
|
|
1036
|
+
const beforeRecord = beforeRecords ?? {};
|
|
542
1037
|
const query = surql.seal(surql.tx([surql.delete("id"), surql.createMutation("delete", "mid", "id")]));
|
|
543
1038
|
await withRetry(this.logger, () => this.local.execute(query, {
|
|
544
1039
|
id: rid,
|
|
545
1040
|
mid: mutationId
|
|
546
1041
|
}));
|
|
547
|
-
|
|
1042
|
+
try {
|
|
1043
|
+
await this.cache.delete(table, id, true, beforeRecord);
|
|
1044
|
+
} catch (err) {
|
|
1045
|
+
this.logger.error({
|
|
1046
|
+
err,
|
|
1047
|
+
id,
|
|
1048
|
+
Category: "sp00ky-client::DataModule::delete"
|
|
1049
|
+
}, "SSP delete-ingest failed; relying on query re-materialize to reflect the delete");
|
|
1050
|
+
}
|
|
1051
|
+
for (const [queryHash, queryState] of this.activeQueries) if (queryState.config.tableName === tableName) try {
|
|
1052
|
+
await this.notifyQuerySynced(queryHash);
|
|
1053
|
+
} catch (err) {
|
|
1054
|
+
this.logger.error({
|
|
1055
|
+
err,
|
|
1056
|
+
queryHash,
|
|
1057
|
+
Category: "sp00ky-client::DataModule::delete"
|
|
1058
|
+
}, "notifyQuerySynced failed after delete");
|
|
1059
|
+
}
|
|
548
1060
|
const mutationEvent = {
|
|
549
1061
|
type: "delete",
|
|
550
1062
|
mutation_id: mutationId,
|
|
@@ -553,7 +1065,7 @@ var DataModule = class {
|
|
|
553
1065
|
for (const callback of this.mutationCallbacks) callback([mutationEvent]);
|
|
554
1066
|
this.logger.debug({
|
|
555
1067
|
id,
|
|
556
|
-
Category: "
|
|
1068
|
+
Category: "sp00ky-client::DataModule::delete"
|
|
557
1069
|
}, "Record deleted");
|
|
558
1070
|
}
|
|
559
1071
|
/**
|
|
@@ -568,14 +1080,14 @@ var DataModule = class {
|
|
|
568
1080
|
this.logger.info({
|
|
569
1081
|
id,
|
|
570
1082
|
tableName,
|
|
571
|
-
Category: "
|
|
1083
|
+
Category: "sp00ky-client::DataModule::rollbackCreate"
|
|
572
1084
|
}, "Rolled back optimistic create");
|
|
573
1085
|
} catch (err) {
|
|
574
1086
|
this.logger.error({
|
|
575
1087
|
err,
|
|
576
1088
|
id,
|
|
577
1089
|
tableName,
|
|
578
|
-
Category: "
|
|
1090
|
+
Category: "sp00ky-client::DataModule::rollbackCreate"
|
|
579
1091
|
}, "Failed to rollback create");
|
|
580
1092
|
}
|
|
581
1093
|
}
|
|
@@ -596,20 +1108,20 @@ var DataModule = class {
|
|
|
596
1108
|
table: tableName,
|
|
597
1109
|
op: "UPDATE",
|
|
598
1110
|
record: parsedRecord,
|
|
599
|
-
version: beforeRecord.
|
|
1111
|
+
version: beforeRecord._00_rv || 1
|
|
600
1112
|
}, true);
|
|
601
1113
|
await this.replaceRecordInQueries(beforeRecord);
|
|
602
1114
|
this.logger.info({
|
|
603
1115
|
id,
|
|
604
1116
|
tableName,
|
|
605
|
-
Category: "
|
|
1117
|
+
Category: "sp00ky-client::DataModule::rollbackUpdate"
|
|
606
1118
|
}, "Rolled back optimistic update");
|
|
607
1119
|
} catch (err) {
|
|
608
1120
|
this.logger.error({
|
|
609
1121
|
err,
|
|
610
1122
|
id,
|
|
611
1123
|
tableName,
|
|
612
|
-
Category: "
|
|
1124
|
+
Category: "sp00ky-client::DataModule::rollbackUpdate"
|
|
613
1125
|
}, "Failed to rollback update");
|
|
614
1126
|
}
|
|
615
1127
|
}
|
|
@@ -637,24 +1149,53 @@ var DataModule = class {
|
|
|
637
1149
|
ttl,
|
|
638
1150
|
tableName
|
|
639
1151
|
});
|
|
640
|
-
const
|
|
1152
|
+
const t0 = performance.now();
|
|
1153
|
+
const { localArray, registrationTimings } = this.cache.registerQuery({
|
|
641
1154
|
queryHash: hash,
|
|
642
1155
|
surql: surqlString,
|
|
643
1156
|
params,
|
|
644
1157
|
ttl: new Duration(ttl),
|
|
645
1158
|
lastActiveAt: /* @__PURE__ */ new Date()
|
|
646
1159
|
});
|
|
647
|
-
|
|
1160
|
+
const registrationTime = performance.now() - t0;
|
|
1161
|
+
queryState.registrationTimings = {
|
|
1162
|
+
parseMs: registrationTimings?.parseMs ?? null,
|
|
1163
|
+
planMs: registrationTimings?.planMs ?? null,
|
|
1164
|
+
snapshotMs: registrationTimings?.snapshotMs ?? null,
|
|
1165
|
+
wallMs: registrationTime
|
|
1166
|
+
};
|
|
1167
|
+
await withRetry(this.logger, () => this.local.query(surql.seal(surql.updateSet("id", [
|
|
1168
|
+
"localArray",
|
|
1169
|
+
"registrationTime",
|
|
1170
|
+
"rowCount"
|
|
1171
|
+
])), {
|
|
648
1172
|
id: recordId,
|
|
649
|
-
localArray
|
|
1173
|
+
localArray,
|
|
1174
|
+
registrationTime,
|
|
1175
|
+
rowCount: localArray.length
|
|
650
1176
|
}));
|
|
1177
|
+
const windowMat = buildWindowMaterialization(surqlString);
|
|
1178
|
+
if (windowMat && localArray.length > 0) try {
|
|
1179
|
+
const winIds = localArray.map(([id]) => parseRecordIdString(id));
|
|
1180
|
+
const [seeded] = await this.local.query(windowMat.query, {
|
|
1181
|
+
...params,
|
|
1182
|
+
__win: winIds
|
|
1183
|
+
});
|
|
1184
|
+
queryState.records = seeded || [];
|
|
1185
|
+
} catch (err) {
|
|
1186
|
+
this.logger.warn({
|
|
1187
|
+
err,
|
|
1188
|
+
hash,
|
|
1189
|
+
Category: "sp00ky-client::DataModule::createAndRegisterQuery"
|
|
1190
|
+
}, "Failed to seed windowed initial records from localArray");
|
|
1191
|
+
}
|
|
651
1192
|
this.activeQueries.set(hash, queryState);
|
|
652
|
-
this.startTTLHeartbeat(queryState);
|
|
1193
|
+
this.startTTLHeartbeat(queryState, hash);
|
|
653
1194
|
this.logger.debug({
|
|
654
1195
|
hash,
|
|
655
1196
|
tableName,
|
|
656
1197
|
recordCount: queryState.records.length,
|
|
657
|
-
Category: "
|
|
1198
|
+
Category: "sp00ky-client::DataModule::query"
|
|
658
1199
|
}, "Query registered");
|
|
659
1200
|
return hash;
|
|
660
1201
|
}
|
|
@@ -671,8 +1212,12 @@ var DataModule = class {
|
|
|
671
1212
|
localArray: [],
|
|
672
1213
|
remoteArray: [],
|
|
673
1214
|
lastActiveAt: /* @__PURE__ */ new Date(),
|
|
1215
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
674
1216
|
ttl,
|
|
675
|
-
tableName
|
|
1217
|
+
tableName,
|
|
1218
|
+
updateCount: 0,
|
|
1219
|
+
rowCount: 0,
|
|
1220
|
+
errorCount: 0
|
|
676
1221
|
}
|
|
677
1222
|
}));
|
|
678
1223
|
configRecord = createdRecord;
|
|
@@ -683,46 +1228,67 @@ var DataModule = class {
|
|
|
683
1228
|
params: parseParams(tableSchema.columns, configRecord.params)
|
|
684
1229
|
};
|
|
685
1230
|
let records = [];
|
|
686
|
-
try {
|
|
1231
|
+
if (buildWindowMaterialization(surqlString) === null) try {
|
|
687
1232
|
const [result] = await this.local.query(surqlString, params);
|
|
688
1233
|
records = result || [];
|
|
689
1234
|
} catch (err) {
|
|
690
1235
|
this.logger.warn({
|
|
691
1236
|
err,
|
|
692
|
-
Category: "
|
|
1237
|
+
Category: "sp00ky-client::DataModule::createNewQuery"
|
|
693
1238
|
}, "Failed to load initial cached records");
|
|
694
1239
|
}
|
|
1240
|
+
const persistedUpdateCount = typeof configRecord?.updateCount === "number" ? configRecord.updateCount : 0;
|
|
1241
|
+
const persistedErrorCount = typeof configRecord?.errorCount === "number" ? configRecord.errorCount : 0;
|
|
695
1242
|
return {
|
|
696
1243
|
config,
|
|
697
1244
|
records,
|
|
698
1245
|
ttlTimer: null,
|
|
699
1246
|
ttlDurationMs: parseDuration(ttl),
|
|
700
|
-
updateCount:
|
|
1247
|
+
updateCount: persistedUpdateCount,
|
|
1248
|
+
materializationSamples: [],
|
|
1249
|
+
lastIngestLatencyMs: null,
|
|
1250
|
+
errorCount: persistedErrorCount,
|
|
1251
|
+
status: "idle",
|
|
1252
|
+
phaseSamples: {},
|
|
1253
|
+
phaseLast: {},
|
|
1254
|
+
registrationTimings: {
|
|
1255
|
+
parseMs: null,
|
|
1256
|
+
planMs: null,
|
|
1257
|
+
snapshotMs: null,
|
|
1258
|
+
wallMs: null
|
|
1259
|
+
}
|
|
701
1260
|
};
|
|
702
1261
|
}
|
|
703
1262
|
async calculateHash(data) {
|
|
704
|
-
const content = JSON.stringify(
|
|
1263
|
+
const content = JSON.stringify({
|
|
1264
|
+
...data,
|
|
1265
|
+
sessionId: this.sessionId
|
|
1266
|
+
});
|
|
705
1267
|
const msgBuffer = new TextEncoder().encode(content);
|
|
706
1268
|
const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
|
|
707
1269
|
return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
708
1270
|
}
|
|
709
|
-
startTTLHeartbeat(queryState) {
|
|
1271
|
+
startTTLHeartbeat(queryState, hash) {
|
|
710
1272
|
if (queryState.ttlTimer) return;
|
|
711
1273
|
const heartbeatTime = Math.floor(queryState.ttlDurationMs * .9);
|
|
712
1274
|
queryState.ttlTimer = setTimeout(() => {
|
|
1275
|
+
queryState.ttlTimer = null;
|
|
1276
|
+
if ((this.subscriptions.get(hash)?.size ?? 0) === 0) {
|
|
1277
|
+
this.logger.debug({
|
|
1278
|
+
hash,
|
|
1279
|
+
Category: "sp00ky-client::DataModule::startTTLHeartbeat"
|
|
1280
|
+
}, "TTL heartbeat: no subscribers, stopping");
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
this.onHeartbeat?.(hash);
|
|
713
1284
|
this.logger.debug({
|
|
1285
|
+
hash,
|
|
714
1286
|
id: encodeRecordId(queryState.config.id),
|
|
715
|
-
Category: "
|
|
716
|
-
}, "TTL heartbeat");
|
|
717
|
-
this.startTTLHeartbeat(queryState);
|
|
1287
|
+
Category: "sp00ky-client::DataModule::startTTLHeartbeat"
|
|
1288
|
+
}, "TTL heartbeat sent");
|
|
1289
|
+
this.startTTLHeartbeat(queryState, hash);
|
|
718
1290
|
}, heartbeatTime);
|
|
719
1291
|
}
|
|
720
|
-
stopTTLHeartbeat(queryState) {
|
|
721
|
-
if (queryState.ttlTimer) {
|
|
722
|
-
clearTimeout(queryState.ttlTimer);
|
|
723
|
-
queryState.ttlTimer = null;
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
1292
|
async replaceRecordInQueries(record) {
|
|
727
1293
|
for (const [queryHash, queryState] of this.activeQueries.entries()) {
|
|
728
1294
|
const index = queryState.records.findIndex((r) => r.id === record.id);
|
|
@@ -744,7 +1310,7 @@ function parseUpdateOptions(id, data, options) {
|
|
|
744
1310
|
let pushEventOptions = {};
|
|
745
1311
|
if (options?.debounced) pushEventOptions = { debounced: {
|
|
746
1312
|
delay: options.debounced !== true ? options.debounced?.delay ?? 200 : 200,
|
|
747
|
-
key: (options.debounced !== true ? options.debounced?.key ?? id : id) === "recordId_x_fields" ? `${id}::${Object.keys(data).
|
|
1313
|
+
key: (options.debounced !== true ? options.debounced?.key ?? id : id) === "recordId_x_fields" ? `${id}::${Object.keys(data).toSorted().join("#")}` : id
|
|
748
1314
|
} };
|
|
749
1315
|
return pushEventOptions;
|
|
750
1316
|
}
|
|
@@ -781,7 +1347,7 @@ var AbstractDatabaseService = class {
|
|
|
781
1347
|
this.logger.debug({
|
|
782
1348
|
query,
|
|
783
1349
|
vars,
|
|
784
|
-
Category: "
|
|
1350
|
+
Category: "sp00ky-client::Database::query"
|
|
785
1351
|
}, "Executing query");
|
|
786
1352
|
const result = await this.client.query(query, vars);
|
|
787
1353
|
const duration = performance.now() - startTime;
|
|
@@ -796,7 +1362,7 @@ var AbstractDatabaseService = class {
|
|
|
796
1362
|
this.logger.trace({
|
|
797
1363
|
query,
|
|
798
1364
|
result,
|
|
799
|
-
Category: "
|
|
1365
|
+
Category: "sp00ky-client::Database::query"
|
|
800
1366
|
}, "Query executed successfully");
|
|
801
1367
|
} catch (err) {
|
|
802
1368
|
const duration = performance.now() - startTime;
|
|
@@ -812,7 +1378,7 @@ var AbstractDatabaseService = class {
|
|
|
812
1378
|
query,
|
|
813
1379
|
vars,
|
|
814
1380
|
err,
|
|
815
|
-
Category: "
|
|
1381
|
+
Category: "sp00ky-client::Database::query"
|
|
816
1382
|
}, "Query execution failed");
|
|
817
1383
|
reject(err);
|
|
818
1384
|
}
|
|
@@ -824,7 +1390,7 @@ var AbstractDatabaseService = class {
|
|
|
824
1390
|
return query.extract(raw);
|
|
825
1391
|
}
|
|
826
1392
|
async close() {
|
|
827
|
-
this.logger.info({ Category: "
|
|
1393
|
+
this.logger.info({ Category: "sp00ky-client::Database::close" }, "Closing database connection");
|
|
828
1394
|
await this.client.close();
|
|
829
1395
|
}
|
|
830
1396
|
};
|
|
@@ -1004,7 +1570,7 @@ var LocalDatabaseService = class extends AbstractDatabaseService {
|
|
|
1004
1570
|
type,
|
|
1005
1571
|
phase,
|
|
1006
1572
|
service: "surrealdb:local",
|
|
1007
|
-
Category: "
|
|
1573
|
+
Category: "sp00ky-client::LocalDatabaseService::diagnostics"
|
|
1008
1574
|
}, `Local SurrealDB diagnostics captured ${type}:${phase}`);
|
|
1009
1575
|
})
|
|
1010
1576
|
}), logger, events);
|
|
@@ -1015,38 +1581,153 @@ var LocalDatabaseService = class extends AbstractDatabaseService {
|
|
|
1015
1581
|
}
|
|
1016
1582
|
async connect() {
|
|
1017
1583
|
const { namespace, database } = this.getConfig();
|
|
1584
|
+
const store = this.getConfig().store ?? "memory";
|
|
1585
|
+
const storeUrl = store === "memory" ? "mem://" : "indxdb://sp00ky";
|
|
1018
1586
|
this.logger.info({
|
|
1019
1587
|
namespace,
|
|
1020
1588
|
database,
|
|
1021
|
-
|
|
1589
|
+
storeUrl,
|
|
1590
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1022
1591
|
}, "Connecting to local database");
|
|
1592
|
+
this.registerUnloadClose();
|
|
1023
1593
|
try {
|
|
1024
|
-
|
|
1025
|
-
this.logger.
|
|
1026
|
-
|
|
1027
|
-
Category: "spooky-client::LocalDatabaseService::connect"
|
|
1028
|
-
}, "[LocalDatabaseService] Calling client.connect");
|
|
1029
|
-
await this.client.connect(storeUrl, {});
|
|
1030
|
-
this.logger.debug({
|
|
1031
|
-
namespace,
|
|
1032
|
-
database,
|
|
1033
|
-
Category: "spooky-client::LocalDatabaseService::connect"
|
|
1034
|
-
}, "[LocalDatabaseService] client.connect returned. Calling client.use");
|
|
1035
|
-
await this.client.use({
|
|
1036
|
-
namespace,
|
|
1037
|
-
database
|
|
1038
|
-
});
|
|
1039
|
-
this.logger.debug({ Category: "spooky-client::LocalDatabaseService::connect" }, "[LocalDatabaseService] client.use returned");
|
|
1040
|
-
this.logger.info({ Category: "spooky-client::LocalDatabaseService::connect" }, "Connected to local database");
|
|
1594
|
+
await this.openStore(storeUrl, namespace, database);
|
|
1595
|
+
this.logger.info({ Category: "sp00ky-client::LocalDatabaseService::connect" }, "Connected to local database");
|
|
1596
|
+
return;
|
|
1041
1597
|
} catch (err) {
|
|
1042
|
-
|
|
1598
|
+
if (store === "memory" || !isLocalStoreOpenError(err)) {
|
|
1599
|
+
this.logger.error({
|
|
1600
|
+
err,
|
|
1601
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1602
|
+
}, "Failed to connect to local database");
|
|
1603
|
+
throw err;
|
|
1604
|
+
}
|
|
1605
|
+
this.logger.warn({
|
|
1043
1606
|
err,
|
|
1044
|
-
Category: "
|
|
1045
|
-
}, "
|
|
1046
|
-
|
|
1607
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1608
|
+
}, "Local IndexedDB store failed to open; retrying before clearing");
|
|
1609
|
+
}
|
|
1610
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
1611
|
+
try {
|
|
1612
|
+
await this.client.close();
|
|
1613
|
+
} catch {}
|
|
1614
|
+
await delay(150 * attempt);
|
|
1615
|
+
try {
|
|
1616
|
+
await this.openStore(storeUrl, namespace, database);
|
|
1617
|
+
this.logger.info({
|
|
1618
|
+
attempt,
|
|
1619
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1620
|
+
}, "Connected to local database on retry (cache preserved)");
|
|
1621
|
+
return;
|
|
1622
|
+
} catch (retryErr) {
|
|
1623
|
+
this.logger.warn({
|
|
1624
|
+
err: retryErr,
|
|
1625
|
+
attempt,
|
|
1626
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1627
|
+
}, "Local store retry failed");
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
try {
|
|
1631
|
+
await this.client.close();
|
|
1632
|
+
} catch {}
|
|
1633
|
+
await dropLocalIndexedDbStores(this.logger);
|
|
1634
|
+
try {
|
|
1635
|
+
await this.openStore(storeUrl, namespace, database);
|
|
1636
|
+
this.logger.info({ Category: "sp00ky-client::LocalDatabaseService::connect" }, "Reconnected to local database after clearing the corrupt store");
|
|
1637
|
+
} catch (retryErr) {
|
|
1638
|
+
this.logger.error({
|
|
1639
|
+
err: retryErr,
|
|
1640
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1641
|
+
}, "Local store still failing after clear; falling back to in-memory");
|
|
1642
|
+
try {
|
|
1643
|
+
await this.client.close();
|
|
1644
|
+
} catch {}
|
|
1645
|
+
await this.openStore("mem://", namespace, database);
|
|
1646
|
+
this.logger.warn({ Category: "sp00ky-client::LocalDatabaseService::connect" }, "Connected to local database (in-memory fallback)");
|
|
1047
1647
|
}
|
|
1048
1648
|
}
|
|
1649
|
+
unloadCloseRegistered = false;
|
|
1650
|
+
/**
|
|
1651
|
+
* Close the local DB on page unload so the SurrealDB-WASM worker releases its
|
|
1652
|
+
* IndexedDB connection cleanly. Without this, the previous page's connection
|
|
1653
|
+
* lingers; the next load's `client.connect` opens the store but the first
|
|
1654
|
+
* write transaction in `client.use` hits an "IndexedDB error" — which then
|
|
1655
|
+
* (mis)triggered the corrupt-store recovery and WIPED the cache on every
|
|
1656
|
+
* reload, making warm loads as slow as cold ones. `pagehide` is the reliable
|
|
1657
|
+
* unload signal (fires on bfcache + normal navigation); `close()` is async but
|
|
1658
|
+
* the WASM worker initiates the IndexedDB connection teardown synchronously.
|
|
1659
|
+
*/
|
|
1660
|
+
registerUnloadClose() {
|
|
1661
|
+
if (this.unloadCloseRegistered || typeof window === "undefined") return;
|
|
1662
|
+
this.unloadCloseRegistered = true;
|
|
1663
|
+
const close = () => {
|
|
1664
|
+
try {
|
|
1665
|
+
this.client.close();
|
|
1666
|
+
} catch {}
|
|
1667
|
+
};
|
|
1668
|
+
window.addEventListener("pagehide", close);
|
|
1669
|
+
window.addEventListener("beforeunload", close);
|
|
1670
|
+
}
|
|
1671
|
+
async openStore(storeUrl, namespace, database) {
|
|
1672
|
+
this.logger.debug({
|
|
1673
|
+
storeUrl,
|
|
1674
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1675
|
+
}, "[LocalDatabaseService] Calling client.connect");
|
|
1676
|
+
await this.client.connect(storeUrl, {});
|
|
1677
|
+
this.logger.debug({
|
|
1678
|
+
namespace,
|
|
1679
|
+
database,
|
|
1680
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1681
|
+
}, "[LocalDatabaseService] client.connect returned. Calling client.use");
|
|
1682
|
+
await this.client.use({
|
|
1683
|
+
namespace,
|
|
1684
|
+
database
|
|
1685
|
+
});
|
|
1686
|
+
this.logger.debug({ Category: "sp00ky-client::LocalDatabaseService::connect" }, "[LocalDatabaseService] client.use returned");
|
|
1687
|
+
}
|
|
1049
1688
|
};
|
|
1689
|
+
function delay(ms) {
|
|
1690
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1691
|
+
}
|
|
1692
|
+
/** True for the SurrealDB-WASM error raised when its IndexedDB-backed key-value
|
|
1693
|
+
* store can't be opened (corrupt / version-incompatible / blocked). Exported
|
|
1694
|
+
* for unit testing the error-message match. */
|
|
1695
|
+
function isLocalStoreOpenError(err) {
|
|
1696
|
+
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
|
1697
|
+
return msg.includes("indexeddb") || msg.includes("idb error") || msg.includes("key-value store");
|
|
1698
|
+
}
|
|
1699
|
+
/** Best-effort delete of this client's IndexedDB store(s). The persistent local
|
|
1700
|
+
* DB lives at `indxdb://sp00ky`; SurrealDB-WASM backs it with one or more
|
|
1701
|
+
* IndexedDB databases whose names include `sp00ky`. Resolves even on
|
|
1702
|
+
* error/blocked so startup can proceed. No-op outside a browser. */
|
|
1703
|
+
async function dropLocalIndexedDbStores(logger) {
|
|
1704
|
+
if (typeof indexedDB === "undefined") return;
|
|
1705
|
+
const remove = (name) => new Promise((resolve) => {
|
|
1706
|
+
try {
|
|
1707
|
+
const req = indexedDB.deleteDatabase(name);
|
|
1708
|
+
req.onsuccess = () => resolve();
|
|
1709
|
+
req.onerror = () => resolve();
|
|
1710
|
+
req.onblocked = () => resolve();
|
|
1711
|
+
} catch {
|
|
1712
|
+
resolve();
|
|
1713
|
+
}
|
|
1714
|
+
});
|
|
1715
|
+
try {
|
|
1716
|
+
let names = [];
|
|
1717
|
+
if (typeof indexedDB.databases === "function") names = (await indexedDB.databases()).map((d) => d.name).filter((n) => !!n && n.toLowerCase().includes("sp00ky"));
|
|
1718
|
+
if (names.length === 0) names = ["sp00ky"];
|
|
1719
|
+
await Promise.all(names.map(remove));
|
|
1720
|
+
logger.info({
|
|
1721
|
+
names,
|
|
1722
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1723
|
+
}, "Cleared local IndexedDB store(s)");
|
|
1724
|
+
} catch (e) {
|
|
1725
|
+
logger.warn({
|
|
1726
|
+
err: e,
|
|
1727
|
+
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
1728
|
+
}, "Failed to enumerate/clear IndexedDB; proceeding anyway");
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1050
1731
|
|
|
1051
1732
|
//#endregion
|
|
1052
1733
|
//#region src/services/database/remote.ts
|
|
@@ -1062,7 +1743,7 @@ var RemoteDatabaseService = class extends AbstractDatabaseService {
|
|
|
1062
1743
|
type,
|
|
1063
1744
|
phase,
|
|
1064
1745
|
service: "surrealdb:remote",
|
|
1065
|
-
Category: "
|
|
1746
|
+
Category: "sp00ky-client::RemoteDatabaseService::diagnostics"
|
|
1066
1747
|
}, `Remote SurrealDB diagnostics captured ${type}:${phase}`);
|
|
1067
1748
|
}) }), logger, events);
|
|
1068
1749
|
this.config = config;
|
|
@@ -1077,7 +1758,7 @@ var RemoteDatabaseService = class extends AbstractDatabaseService {
|
|
|
1077
1758
|
endpoint,
|
|
1078
1759
|
namespace,
|
|
1079
1760
|
database,
|
|
1080
|
-
Category: "
|
|
1761
|
+
Category: "sp00ky-client::RemoteDatabaseService::connect"
|
|
1081
1762
|
}, "Connecting to remote database");
|
|
1082
1763
|
try {
|
|
1083
1764
|
await this.client.connect(endpoint);
|
|
@@ -1086,18 +1767,18 @@ var RemoteDatabaseService = class extends AbstractDatabaseService {
|
|
|
1086
1767
|
database
|
|
1087
1768
|
});
|
|
1088
1769
|
if (token) {
|
|
1089
|
-
this.logger.debug({ Category: "
|
|
1770
|
+
this.logger.debug({ Category: "sp00ky-client::RemoteDatabaseService::connect" }, "Authenticating with token");
|
|
1090
1771
|
await this.client.authenticate(token);
|
|
1091
1772
|
}
|
|
1092
|
-
this.logger.info({ Category: "
|
|
1773
|
+
this.logger.info({ Category: "sp00ky-client::RemoteDatabaseService::connect" }, "Connected to remote database");
|
|
1093
1774
|
} catch (err) {
|
|
1094
1775
|
this.logger.error({
|
|
1095
1776
|
err,
|
|
1096
|
-
Category: "
|
|
1777
|
+
Category: "sp00ky-client::RemoteDatabaseService::connect"
|
|
1097
1778
|
}, "Failed to connect to remote database");
|
|
1098
1779
|
throw err;
|
|
1099
1780
|
}
|
|
1100
|
-
} else this.logger.warn({ Category: "
|
|
1781
|
+
} else this.logger.warn({ Category: "sp00ky-client::RemoteDatabaseService::connect" }, "No endpoint configured for remote database");
|
|
1101
1782
|
}
|
|
1102
1783
|
async signin(params) {
|
|
1103
1784
|
return this.client.signin(params);
|
|
@@ -1115,70 +1796,14 @@ var RemoteDatabaseService = class extends AbstractDatabaseService {
|
|
|
1115
1796
|
|
|
1116
1797
|
//#endregion
|
|
1117
1798
|
//#region src/services/logger/index.ts
|
|
1118
|
-
|
|
1119
|
-
function mapLevelToSeverityNumber(level) {
|
|
1120
|
-
switch (level) {
|
|
1121
|
-
case "trace": return 1;
|
|
1122
|
-
case "debug": return 5;
|
|
1123
|
-
case "info": return 9;
|
|
1124
|
-
case "warn": return 13;
|
|
1125
|
-
case "error": return 17;
|
|
1126
|
-
case "fatal": return 21;
|
|
1127
|
-
default: return 9;
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
function createLogger(level = "info", otelEndpoint) {
|
|
1799
|
+
function createLogger(level = "info", transmit) {
|
|
1131
1800
|
const browserConfig = {
|
|
1132
1801
|
asObject: true,
|
|
1133
1802
|
write: (o) => {
|
|
1134
1803
|
console.log(JSON.stringify(o));
|
|
1135
1804
|
}
|
|
1136
1805
|
};
|
|
1137
|
-
if (
|
|
1138
|
-
const loggerProvider = new LoggerProvider({
|
|
1139
|
-
resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "spooky-client" }),
|
|
1140
|
-
processors: [new BatchLogRecordProcessor(new OTLPLogExporter({ url: otelEndpoint }))]
|
|
1141
|
-
});
|
|
1142
|
-
const otelLogger = {};
|
|
1143
|
-
const getOtelLogger = (category) => {
|
|
1144
|
-
if (!otelLogger[category]) otelLogger[category] = loggerProvider.getLogger(category);
|
|
1145
|
-
return otelLogger[category];
|
|
1146
|
-
};
|
|
1147
|
-
browserConfig.transmit = {
|
|
1148
|
-
level,
|
|
1149
|
-
send: (levelLabel, logEvent) => {
|
|
1150
|
-
try {
|
|
1151
|
-
const messages = [...logEvent.messages];
|
|
1152
|
-
const severityNumber = mapLevelToSeverityNumber(levelLabel);
|
|
1153
|
-
let body = "";
|
|
1154
|
-
const msg = messages.pop();
|
|
1155
|
-
if (typeof msg === "string") body = msg;
|
|
1156
|
-
else if (msg) body = JSON.stringify(msg);
|
|
1157
|
-
let category = "spooky-client::unknown";
|
|
1158
|
-
const attributes = {};
|
|
1159
|
-
for (const msg of messages) if (typeof msg === "object") {
|
|
1160
|
-
if (msg.Category) {
|
|
1161
|
-
category = msg.Category;
|
|
1162
|
-
delete msg.Category;
|
|
1163
|
-
}
|
|
1164
|
-
Object.assign(attributes, msg);
|
|
1165
|
-
}
|
|
1166
|
-
getOtelLogger(category).emit({
|
|
1167
|
-
severityNumber,
|
|
1168
|
-
severityText: levelLabel.toUpperCase(),
|
|
1169
|
-
body,
|
|
1170
|
-
attributes: {
|
|
1171
|
-
...logEvent.bindings[0],
|
|
1172
|
-
...attributes
|
|
1173
|
-
},
|
|
1174
|
-
timestamp: new Date(logEvent.ts)
|
|
1175
|
-
});
|
|
1176
|
-
} catch (e) {
|
|
1177
|
-
console.warn("Failed to transmit log to OTEL endpoint", e);
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
};
|
|
1181
|
-
}
|
|
1806
|
+
if (transmit) browserConfig.transmit = transmit;
|
|
1182
1807
|
return pino({
|
|
1183
1808
|
level,
|
|
1184
1809
|
browser: browserConfig
|
|
@@ -1203,25 +1828,25 @@ var LocalMigrator = class {
|
|
|
1203
1828
|
const hash = await sha1(schemaSurql);
|
|
1204
1829
|
const { database } = this.localDb.getConfig();
|
|
1205
1830
|
if (await this.isSchemaUpToDate(hash)) {
|
|
1206
|
-
this.logger.info({ Category: "
|
|
1831
|
+
this.logger.info({ Category: "sp00ky-client::LocalMigrator::provision" }, "[Provisioning] Schema is up to date, skipping migration");
|
|
1207
1832
|
return;
|
|
1208
1833
|
}
|
|
1209
1834
|
await this.recreateDatabase(database);
|
|
1210
|
-
const fullSchema = schemaSurql + "\n\n DEFINE TABLE IF NOT EXISTS
|
|
1835
|
+
const fullSchema = schemaSurql + "\n\n DEFINE TABLE IF NOT EXISTS _00_stream_processor_state SCHEMALESS PERMISSIONS FOR select, create, update, delete WHERE true;\n DEFINE TABLE IF NOT EXISTS _00_query SCHEMALESS PERMISSIONS FOR select, create, update, delete WHERE true;\n DEFINE TABLE IF NOT EXISTS _00_schema SCHEMALESS PERMISSIONS FOR select, create, update, delete WHERE true;\n DEFINE TABLE IF NOT EXISTS _00_pending_mutations SCHEMALESS PERMISSIONS FOR select, create, update, delete WHERE true;\n ";
|
|
1211
1836
|
const statements = this.splitStatements(fullSchema);
|
|
1212
1837
|
for (let i = 0; i < statements.length; i++) {
|
|
1213
1838
|
const statement = statements[i];
|
|
1214
1839
|
const cleanStatement = statement.replace(/--.*/g, "").trim();
|
|
1215
1840
|
if (cleanStatement.toUpperCase().startsWith("DEFINE INDEX")) {
|
|
1216
|
-
this.logger.warn({ Category: "
|
|
1841
|
+
this.logger.warn({ Category: "sp00ky-client::LocalMigrator::provision" }, `[Provisioning] Skipping index definition (WASM hang avoidance): ${cleanStatement.substring(0, 50)}...`);
|
|
1217
1842
|
continue;
|
|
1218
1843
|
}
|
|
1219
1844
|
try {
|
|
1220
|
-
this.logger.info({ Category: "
|
|
1845
|
+
this.logger.info({ Category: "sp00ky-client::LocalMigrator::provision" }, `[Provisioning] (${i + 1}/${statements.length}) Executing: ${statement.substring(0, 50)}...`);
|
|
1221
1846
|
await this.localDb.query(statement);
|
|
1222
|
-
this.logger.info({ Category: "
|
|
1847
|
+
this.logger.info({ Category: "sp00ky-client::LocalMigrator::provision" }, `[Provisioning] (${i + 1}/${statements.length}) Done`);
|
|
1223
1848
|
} catch (e) {
|
|
1224
|
-
this.logger.error({ Category: "
|
|
1849
|
+
this.logger.error({ Category: "sp00ky-client::LocalMigrator::provision" }, `[Provisioning] (${i + 1}/${statements.length}) Error executing statement: ${statement}`);
|
|
1225
1850
|
throw e;
|
|
1226
1851
|
}
|
|
1227
1852
|
}
|
|
@@ -1229,22 +1854,22 @@ var LocalMigrator = class {
|
|
|
1229
1854
|
}
|
|
1230
1855
|
async isSchemaUpToDate(hash) {
|
|
1231
1856
|
try {
|
|
1232
|
-
const [lastSchemaRecord] = await this.localDb.query(`SELECT hash, created_at FROM ONLY
|
|
1857
|
+
const [lastSchemaRecord] = await this.localDb.query(`SELECT hash, created_at FROM ONLY _00_schema ORDER BY created_at DESC LIMIT 1;`);
|
|
1233
1858
|
return lastSchemaRecord?.hash === hash;
|
|
1234
|
-
} catch (
|
|
1859
|
+
} catch (_error) {
|
|
1235
1860
|
return false;
|
|
1236
1861
|
}
|
|
1237
1862
|
}
|
|
1238
1863
|
async recreateDatabase(database) {
|
|
1239
1864
|
try {
|
|
1240
|
-
await this.localDb.query(`DEFINE DATABASE
|
|
1241
|
-
} catch (
|
|
1865
|
+
await this.localDb.query(`DEFINE DATABASE _00_temp;`);
|
|
1866
|
+
} catch (_e) {}
|
|
1242
1867
|
try {
|
|
1243
1868
|
await this.localDb.query(`
|
|
1244
|
-
USE DB
|
|
1869
|
+
USE DB _00_temp;
|
|
1245
1870
|
REMOVE DATABASE ${database};
|
|
1246
1871
|
`);
|
|
1247
|
-
} catch (
|
|
1872
|
+
} catch (_e) {}
|
|
1248
1873
|
await this.localDb.query(`
|
|
1249
1874
|
DEFINE DATABASE ${database};
|
|
1250
1875
|
USE DB ${database};
|
|
@@ -1302,7 +1927,7 @@ var LocalMigrator = class {
|
|
|
1302
1927
|
return statements;
|
|
1303
1928
|
}
|
|
1304
1929
|
async createHashRecord(hash) {
|
|
1305
|
-
await this.localDb.query(`UPSERT
|
|
1930
|
+
await this.localDb.query(`UPSERT _00_schema SET hash = $hash, created_at = time::now() WHERE hash = $hash;`, { hash });
|
|
1306
1931
|
}
|
|
1307
1932
|
};
|
|
1308
1933
|
|
|
@@ -1394,7 +2019,7 @@ var UpQueue = class {
|
|
|
1394
2019
|
this.logger.error({
|
|
1395
2020
|
error,
|
|
1396
2021
|
event,
|
|
1397
|
-
Category: "
|
|
2022
|
+
Category: "sp00ky-client::UpQueue::next"
|
|
1398
2023
|
}, "Network error processing mutation, re-queuing");
|
|
1399
2024
|
this.queue.unshift(event);
|
|
1400
2025
|
throw error;
|
|
@@ -1402,7 +2027,7 @@ var UpQueue = class {
|
|
|
1402
2027
|
this.logger.error({
|
|
1403
2028
|
error,
|
|
1404
2029
|
event,
|
|
1405
|
-
Category: "
|
|
2030
|
+
Category: "sp00ky-client::UpQueue::next"
|
|
1406
2031
|
}, "Application error processing mutation, rolling back");
|
|
1407
2032
|
try {
|
|
1408
2033
|
await this.removeEventFromDatabase(event.mutation_id);
|
|
@@ -1410,7 +2035,7 @@ var UpQueue = class {
|
|
|
1410
2035
|
this.logger.error({
|
|
1411
2036
|
error: removeError,
|
|
1412
2037
|
event,
|
|
1413
|
-
Category: "
|
|
2038
|
+
Category: "sp00ky-client::UpQueue::next"
|
|
1414
2039
|
}, "Failed to remove rolled-back mutation from database");
|
|
1415
2040
|
}
|
|
1416
2041
|
if (onRollback) try {
|
|
@@ -1419,7 +2044,7 @@ var UpQueue = class {
|
|
|
1419
2044
|
this.logger.error({
|
|
1420
2045
|
error: rollbackError,
|
|
1421
2046
|
event,
|
|
1422
|
-
Category: "
|
|
2047
|
+
Category: "sp00ky-client::UpQueue::next"
|
|
1423
2048
|
}, "Rollback handler failed");
|
|
1424
2049
|
}
|
|
1425
2050
|
this._events.addEvent({
|
|
@@ -1434,7 +2059,7 @@ var UpQueue = class {
|
|
|
1434
2059
|
this.logger.error({
|
|
1435
2060
|
error,
|
|
1436
2061
|
event,
|
|
1437
|
-
Category: "
|
|
2062
|
+
Category: "sp00ky-client::UpQueue::next"
|
|
1438
2063
|
}, "Failed to remove mutation from database after successful processing");
|
|
1439
2064
|
}
|
|
1440
2065
|
this._events.addEvent({
|
|
@@ -1448,7 +2073,7 @@ var UpQueue = class {
|
|
|
1448
2073
|
}
|
|
1449
2074
|
async loadFromDatabase() {
|
|
1450
2075
|
try {
|
|
1451
|
-
const [records] = await this.local.query(`SELECT * FROM
|
|
2076
|
+
const [records] = await this.local.query(`SELECT * FROM _00_pending_mutations ORDER BY created_at ASC`);
|
|
1452
2077
|
this.queue = records.map((r) => {
|
|
1453
2078
|
switch (r.mutationType) {
|
|
1454
2079
|
case "create": return {
|
|
@@ -1474,7 +2099,7 @@ var UpQueue = class {
|
|
|
1474
2099
|
this.logger.warn({
|
|
1475
2100
|
mutationType: r.mutationType,
|
|
1476
2101
|
record: r,
|
|
1477
|
-
Category: "
|
|
2102
|
+
Category: "sp00ky-client::UpQueue::loadFromDatabase"
|
|
1478
2103
|
}, "Unknown mutation type");
|
|
1479
2104
|
return null;
|
|
1480
2105
|
}
|
|
@@ -1482,7 +2107,7 @@ var UpQueue = class {
|
|
|
1482
2107
|
} catch (error) {
|
|
1483
2108
|
this.logger.error({
|
|
1484
2109
|
error,
|
|
1485
|
-
Category: "
|
|
2110
|
+
Category: "sp00ky-client::UpQueue::loadFromDatabase"
|
|
1486
2111
|
}, "Failed to load pending mutations from database");
|
|
1487
2112
|
}
|
|
1488
2113
|
}
|
|
@@ -1523,7 +2148,7 @@ var DownQueue = class {
|
|
|
1523
2148
|
this.logger.error({
|
|
1524
2149
|
error,
|
|
1525
2150
|
event,
|
|
1526
|
-
Category: "
|
|
2151
|
+
Category: "sp00ky-client::DownQueue::next"
|
|
1527
2152
|
}, "Failed to process query");
|
|
1528
2153
|
this.queue.unshift(event);
|
|
1529
2154
|
throw error;
|
|
@@ -1538,8 +2163,8 @@ var ArraySyncer = class {
|
|
|
1538
2163
|
remoteArray;
|
|
1539
2164
|
needsSort = false;
|
|
1540
2165
|
constructor(localArray, remoteArray) {
|
|
1541
|
-
this.remoteArray = remoteArray.
|
|
1542
|
-
this.localArray = localArray.
|
|
2166
|
+
this.remoteArray = remoteArray.toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
2167
|
+
this.localArray = localArray.toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
1543
2168
|
}
|
|
1544
2169
|
/**
|
|
1545
2170
|
* Inserts an item into the local array
|
|
@@ -1575,7 +2200,6 @@ var ArraySyncer = class {
|
|
|
1575
2200
|
this.localArray.sort((a, b) => a[0].localeCompare(b[0]));
|
|
1576
2201
|
this.needsSort = false;
|
|
1577
2202
|
}
|
|
1578
|
-
console.log("xxxx555", this.localArray, this.remoteArray);
|
|
1579
2203
|
return diffRecordVersionArray(this.localArray, this.remoteArray);
|
|
1580
2204
|
}
|
|
1581
2205
|
};
|
|
@@ -1606,14 +2230,12 @@ function diffRecordVersionArray(local, remote) {
|
|
|
1606
2230
|
};
|
|
1607
2231
|
}
|
|
1608
2232
|
function createDiffFromDbOp(op, recordId, version, versions) {
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
};
|
|
1616
|
-
}
|
|
2233
|
+
const old = versions?.find((record) => record[0] === encodeRecordId(recordId));
|
|
2234
|
+
if (old && old[1] >= version) return {
|
|
2235
|
+
added: [],
|
|
2236
|
+
updated: [],
|
|
2237
|
+
removed: []
|
|
2238
|
+
};
|
|
1617
2239
|
if (op === "CREATE") return {
|
|
1618
2240
|
added: [{
|
|
1619
2241
|
id: recordId,
|
|
@@ -1636,6 +2258,98 @@ function createDiffFromDbOp(op, recordId, version, versions) {
|
|
|
1636
2258
|
removed: [recordId]
|
|
1637
2259
|
};
|
|
1638
2260
|
}
|
|
2261
|
+
/**
|
|
2262
|
+
* Default cadence for the `_00_list_ref_user_<id>` poll fallback. The
|
|
2263
|
+
* poll is the safety net for SurrealDB v3's occasionally-dropped LIVE
|
|
2264
|
+
* deliveries; 500ms is aggressive enough to feel real-time on the
|
|
2265
|
+
* happy path while keeping the per-session query load bounded.
|
|
2266
|
+
*/
|
|
2267
|
+
const DEFAULT_LIST_REF_POLL_INTERVAL_MS = 500;
|
|
2268
|
+
/**
|
|
2269
|
+
* Build the SurrealQL select that powers both the initial-fetch and
|
|
2270
|
+
* the periodic poll of `_00_list_ref[_user_<id>]`. The `parent IS NONE`
|
|
2271
|
+
* predicate excludes subquery entries (rows with `parent_rel` set)
|
|
2272
|
+
* because the client's `RecordVersionArray` only tracks primary rows;
|
|
2273
|
+
* including subquery rows would surface them as spurious "added"
|
|
2274
|
+
* diffs every tick.
|
|
2275
|
+
*/
|
|
2276
|
+
function buildListRefSelect(table) {
|
|
2277
|
+
return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NONE`;
|
|
2278
|
+
}
|
|
2279
|
+
/**
|
|
2280
|
+
* Build the SurrealQL select for a query's SUBQUERY child edges — the
|
|
2281
|
+
* mirror of {@link buildListRefSelect}. `.related()` queries register a
|
|
2282
|
+
* correlated subquery; the SSP materializes each matched child as a
|
|
2283
|
+
* `_00_list_ref` edge tagged with `parent`/`parent_rel` (see
|
|
2284
|
+
* `apps/ssp` edge writer). `parent IS NONE` (the primary select) drops
|
|
2285
|
+
* these, so their bodies never reach the local cache and a cold-reload
|
|
2286
|
+
* re-materialization of the correlated surql yields empty related
|
|
2287
|
+
* fields. This `parent IS NOT NONE` variant pulls the child `out`+`version`
|
|
2288
|
+
* pairs (any nesting depth) so we can sync their bodies into the local
|
|
2289
|
+
* store SEPARATELY from the primary window array.
|
|
2290
|
+
*/
|
|
2291
|
+
function buildSubqueryListRefSelect(table) {
|
|
2292
|
+
return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NOT NONE`;
|
|
2293
|
+
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Resolve the effective list-ref poll interval. Negative or zero
|
|
2296
|
+
* values fall back to the default — accepting them would either
|
|
2297
|
+
* disable polling silently or busy-loop the event loop.
|
|
2298
|
+
*/
|
|
2299
|
+
function resolveListRefPollInterval(opt) {
|
|
2300
|
+
if (typeof opt !== "number" || !Number.isFinite(opt) || opt <= 0) return DEFAULT_LIST_REF_POLL_INTERVAL_MS;
|
|
2301
|
+
return opt;
|
|
2302
|
+
}
|
|
2303
|
+
/**
|
|
2304
|
+
* Ceiling for the adaptive list_ref poll backoff. An idle page (no LIVE
|
|
2305
|
+
* events, no poll-detected list_ref changes) coasts up to this cadence;
|
|
2306
|
+
* the existing healthy-LIVE safety net runs at the same 5s, so this keeps
|
|
2307
|
+
* the worst-case catch-up latency for a missed cross-session change at the
|
|
2308
|
+
* cadence the codebase already treats as acceptable.
|
|
2309
|
+
*/
|
|
2310
|
+
const LIST_REF_POLL_MAX_INTERVAL_MS = 5e3;
|
|
2311
|
+
/**
|
|
2312
|
+
* Adaptive poll delay: stay at the responsive `baseIntervalMs` while
|
|
2313
|
+
* changes are arriving, and exponentially back off toward `maxIntervalMs`
|
|
2314
|
+
* while the `_00_list_ref` is quiet.
|
|
2315
|
+
*
|
|
2316
|
+
* `idleStreak` is the count of consecutive poll cycles that observed *no*
|
|
2317
|
+
* change. `Sp00kySync` resets it to 0 whenever a poll detects a real
|
|
2318
|
+
* remoteArray change OR a LIVE event lands, so any activity snaps the poll
|
|
2319
|
+
* straight back to `baseIntervalMs`. A streak of 0 (something just
|
|
2320
|
+
* happened) → base; otherwise `base * 2^streak` capped at `maxIntervalMs`.
|
|
2321
|
+
*
|
|
2322
|
+
* This replaces {@link nextPollDelayMs}: the old helper slowed the poll
|
|
2323
|
+
* only while LIVE was *delivering*, but the cross-session LIVE-permission
|
|
2324
|
+
* gap means LIVE frequently never fires here, so it left a fully idle page
|
|
2325
|
+
* polling every `base` ms forever (the "continuous queries while idle"
|
|
2326
|
+
* symptom). Backing off on observed idleness instead covers the
|
|
2327
|
+
* LIVE-healthy case for free (LIVE applies the change → the next poll sees
|
|
2328
|
+
* nothing new → the streak grows → it backs off).
|
|
2329
|
+
*/
|
|
2330
|
+
function listRefPollDelayMs(args) {
|
|
2331
|
+
const { idleStreak, baseIntervalMs, maxIntervalMs = LIST_REF_POLL_MAX_INTERVAL_MS } = args;
|
|
2332
|
+
const cap = Math.max(baseIntervalMs, maxIntervalMs);
|
|
2333
|
+
if (idleStreak <= 0) return baseIntervalMs;
|
|
2334
|
+
const exponent = Math.min(idleStreak, 30);
|
|
2335
|
+
return Math.min(baseIntervalMs * 2 ** exponent, cap);
|
|
2336
|
+
}
|
|
2337
|
+
/**
|
|
2338
|
+
* Order-insensitive equality for two `RecordVersionArray`s (each a list of
|
|
2339
|
+
* `[recordIdString, version]`). The `_00_list_ref` SELECT has no `ORDER
|
|
2340
|
+
* BY`, so row order can differ between polls without anything having
|
|
2341
|
+
* actually changed — comparing as an id→version map avoids false
|
|
2342
|
+
* "changed" verdicts that would defeat the idle backoff. Record ids are
|
|
2343
|
+
* unique within a query's list_ref, so a map is a faithful representation.
|
|
2344
|
+
*/
|
|
2345
|
+
function recordVersionArraysEqual(a, b) {
|
|
2346
|
+
if (a === b) return true;
|
|
2347
|
+
if (a.length !== b.length) return false;
|
|
2348
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2349
|
+
for (const [id, version] of a) byId.set(id, version);
|
|
2350
|
+
for (const [id, version] of b) if (byId.get(id) !== version) return false;
|
|
2351
|
+
return true;
|
|
2352
|
+
}
|
|
1639
2353
|
|
|
1640
2354
|
//#endregion
|
|
1641
2355
|
//#region src/modules/sync/engine.ts
|
|
@@ -1643,7 +2357,7 @@ function createDiffFromDbOp(op, recordId, version, versions) {
|
|
|
1643
2357
|
* SyncEngine handles the core sync operations: fetching remote records,
|
|
1644
2358
|
* caching them locally, and ingesting into DBSP.
|
|
1645
2359
|
*
|
|
1646
|
-
* This is extracted from
|
|
2360
|
+
* This is extracted from Sp00kySync to separate "how to sync" from "when to sync".
|
|
1647
2361
|
*/
|
|
1648
2362
|
var SyncEngine = class {
|
|
1649
2363
|
logger;
|
|
@@ -1652,7 +2366,7 @@ var SyncEngine = class {
|
|
|
1652
2366
|
this.remote = remote;
|
|
1653
2367
|
this.cache = cache;
|
|
1654
2368
|
this.schema = schema;
|
|
1655
|
-
this.logger = logger.child({ service: "
|
|
2369
|
+
this.logger = logger.child({ service: "Sp00kySync:SyncEngine" });
|
|
1656
2370
|
}
|
|
1657
2371
|
/**
|
|
1658
2372
|
* Sync missing/updated/removed records between local and remote.
|
|
@@ -1665,33 +2379,42 @@ var SyncEngine = class {
|
|
|
1665
2379
|
added,
|
|
1666
2380
|
updated,
|
|
1667
2381
|
removed,
|
|
1668
|
-
Category: "
|
|
2382
|
+
Category: "sp00ky-client::SyncEngine::syncRecords"
|
|
1669
2383
|
}, "SyncEngine.syncRecords diff");
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
const
|
|
1674
|
-
|
|
2384
|
+
let stillRemoteIds = [];
|
|
2385
|
+
if (removed.length > 0) stillRemoteIds = await this.handleRemovedRecords(removed);
|
|
2386
|
+
const toFetch = [...added, ...updated];
|
|
2387
|
+
const idsToFetch = toFetch.map((x) => x.id);
|
|
2388
|
+
if (idsToFetch.length === 0) return {
|
|
2389
|
+
remoteFetchMs: 0,
|
|
2390
|
+
stillRemoteIds
|
|
2391
|
+
};
|
|
2392
|
+
const versionMap = /* @__PURE__ */ new Map();
|
|
2393
|
+
for (const item of toFetch) versionMap.set(encodeRecordId(item.id), item.version);
|
|
2394
|
+
const remoteFetchStart = performance.now();
|
|
2395
|
+
const [remoteResults] = await this.remote.query("SELECT * FROM $idsToFetch", { idsToFetch });
|
|
2396
|
+
const remoteFetchMs = performance.now() - remoteFetchStart;
|
|
1675
2397
|
const cacheBatch = [];
|
|
1676
|
-
for (const
|
|
2398
|
+
for (const record of remoteResults) {
|
|
1677
2399
|
if (!record?.id) {
|
|
1678
2400
|
this.logger.warn({
|
|
1679
2401
|
record,
|
|
1680
2402
|
idsToFetch,
|
|
1681
|
-
Category: "
|
|
1682
|
-
}, "Remote record has no id. Skipping record");
|
|
2403
|
+
Category: "sp00ky-client::SyncEngine::syncRecords"
|
|
2404
|
+
}, "Remote record has no id (possibly deleted). Skipping record");
|
|
1683
2405
|
continue;
|
|
1684
2406
|
}
|
|
1685
2407
|
const fullId = encodeRecordId(record.id);
|
|
1686
2408
|
const table = record.id.table.toString();
|
|
1687
2409
|
const isAdded = added.some((item) => encodeRecordId(item.id) === fullId);
|
|
2410
|
+
const version = versionMap.get(fullId) ?? 0;
|
|
1688
2411
|
const localVersion = this.cache.lookup(fullId);
|
|
1689
|
-
if (localVersion &&
|
|
2412
|
+
if (localVersion && version <= localVersion) {
|
|
1690
2413
|
this.logger.info({
|
|
1691
2414
|
recordId: fullId,
|
|
1692
|
-
version
|
|
2415
|
+
version,
|
|
1693
2416
|
localVersion,
|
|
1694
|
-
Category: "
|
|
2417
|
+
Category: "sp00ky-client::SyncEngine::syncRecords"
|
|
1695
2418
|
}, "Local version is higher than remote version. Skipping record");
|
|
1696
2419
|
continue;
|
|
1697
2420
|
}
|
|
@@ -1701,37 +2424,59 @@ var SyncEngine = class {
|
|
|
1701
2424
|
table,
|
|
1702
2425
|
op: isAdded ? "CREATE" : "UPDATE",
|
|
1703
2426
|
record: cleanedRecord,
|
|
1704
|
-
version
|
|
2427
|
+
version
|
|
1705
2428
|
});
|
|
1706
2429
|
}
|
|
1707
2430
|
if (cacheBatch.length > 0) await this.cache.saveBatch(cacheBatch);
|
|
1708
2431
|
this.events.emit(SyncEventTypes.RemoteDataIngested, { records: remoteResults });
|
|
2432
|
+
return {
|
|
2433
|
+
remoteFetchMs,
|
|
2434
|
+
stillRemoteIds
|
|
2435
|
+
};
|
|
1709
2436
|
}
|
|
1710
2437
|
/**
|
|
1711
2438
|
* Handle records that exist locally but not in remote array.
|
|
2439
|
+
*
|
|
2440
|
+
* "Removed" here is a derived signal: the SSP's `_00_list_ref` array no
|
|
2441
|
+
* longer references a record that exists locally. That can mean the row
|
|
2442
|
+
* was genuinely deleted upstream — but it can also be a benign race
|
|
2443
|
+
* (e.g. a record we just created hasn't propagated into the SSP's
|
|
2444
|
+
* incantation list yet). Before deleting locally we verify against
|
|
2445
|
+
* upstream SurrealDB: if the row still exists there, skip the delete.
|
|
2446
|
+
*
|
|
2447
|
+
* On verification failure we skip deletion too. Losing a stale local
|
|
2448
|
+
* row to a later sync round is recoverable; deleting a fresh row that
|
|
2449
|
+
* upstream still has is not.
|
|
1712
2450
|
*/
|
|
1713
2451
|
async handleRemovedRecords(removed) {
|
|
1714
2452
|
this.logger.debug({
|
|
1715
2453
|
removed: removed.map((r) => r.toString()),
|
|
1716
|
-
Category: "
|
|
2454
|
+
Category: "sp00ky-client::SyncEngine::handleRemovedRecords"
|
|
1717
2455
|
}, "Checking removed records");
|
|
1718
|
-
let existingRemoteIds
|
|
2456
|
+
let existingRemoteIds;
|
|
1719
2457
|
try {
|
|
1720
|
-
const [
|
|
1721
|
-
existingRemoteIds = new Set(
|
|
1722
|
-
} catch {
|
|
1723
|
-
this.logger.
|
|
2458
|
+
const [existing] = await this.remote.query("SELECT id FROM $ids", { ids: removed });
|
|
2459
|
+
existingRemoteIds = new Set((existing ?? []).map((row) => encodeRecordId(row.id)));
|
|
2460
|
+
} catch (err) {
|
|
2461
|
+
this.logger.warn({
|
|
2462
|
+
err,
|
|
2463
|
+
removed: removed.map((r) => r.toString()),
|
|
2464
|
+
Category: "sp00ky-client::SyncEngine::handleRemovedRecords"
|
|
2465
|
+
}, "Remote existence check failed, skipping deletion to avoid clobbering fresh data");
|
|
2466
|
+
return [];
|
|
1724
2467
|
}
|
|
2468
|
+
const stillRemoteIds = [];
|
|
1725
2469
|
for (const recordId of removed) {
|
|
1726
2470
|
const recordIdStr = encodeRecordId(recordId);
|
|
1727
2471
|
if (!existingRemoteIds.has(recordIdStr)) {
|
|
1728
2472
|
this.logger.debug({
|
|
1729
2473
|
recordId: recordIdStr,
|
|
1730
|
-
Category: "
|
|
2474
|
+
Category: "sp00ky-client::SyncEngine::handleRemovedRecords"
|
|
1731
2475
|
}, "Deleting confirmed removed record");
|
|
1732
2476
|
await this.cache.delete(recordId.table.name, recordIdStr);
|
|
1733
|
-
}
|
|
2477
|
+
} else stillRemoteIds.push(recordIdStr);
|
|
1734
2478
|
}
|
|
2479
|
+
return stillRemoteIds;
|
|
1735
2480
|
}
|
|
1736
2481
|
};
|
|
1737
2482
|
|
|
@@ -1803,23 +2548,82 @@ var SyncScheduler = class {
|
|
|
1803
2548
|
}
|
|
1804
2549
|
};
|
|
1805
2550
|
|
|
2551
|
+
//#endregion
|
|
2552
|
+
//#region src/modules/ref-tables.ts
|
|
2553
|
+
/**
|
|
2554
|
+
* Default ref-storage mode for this client build. Mirrors the SSP's
|
|
2555
|
+
* default (`RefMode::Dedicated`) so cross-session sync works out of the
|
|
2556
|
+
* box.
|
|
2557
|
+
*/
|
|
2558
|
+
const DEFAULT_REF_MODE = "dedicated";
|
|
2559
|
+
/**
|
|
2560
|
+
* Sanitize a user record id (e.g. `"user:abc"`) into the segment that
|
|
2561
|
+
* goes into a dedicated table name (e.g. `"abc"`). Returns `null` if
|
|
2562
|
+
* the id is missing the `user:` prefix or contains characters that
|
|
2563
|
+
* aren't valid in a SurrealDB table identifier — the server-side
|
|
2564
|
+
* `ssp_protocol::sanitize_user_id` uses the same predicate.
|
|
2565
|
+
*
|
|
2566
|
+
* Accepts both string ids (`"user:abc"`) and SurrealDB `RecordId`
|
|
2567
|
+
* objects (which only stringify cleanly via `.toString()`), since
|
|
2568
|
+
* `AuthService` passes the record-id object as-is to its subscribers.
|
|
2569
|
+
*/
|
|
2570
|
+
function sanitizeUserId(userId) {
|
|
2571
|
+
if (userId === null || userId === void 0) return null;
|
|
2572
|
+
const asString = typeof userId === "string" ? userId : typeof userId.toString === "function" ? userId.toString() : null;
|
|
2573
|
+
if (!asString) return null;
|
|
2574
|
+
const raw = asString.startsWith("user:") ? asString.slice(5) : asString;
|
|
2575
|
+
if (raw.length === 0) return null;
|
|
2576
|
+
if (!/^[A-Za-z0-9_]+$/.test(raw)) return null;
|
|
2577
|
+
return raw;
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* Returns the `_00_list_ref` table name for `(mode, userId)`. Falls
|
|
2581
|
+
* back to the global `_00_list_ref` when sanitization fails or in
|
|
2582
|
+
* single mode.
|
|
2583
|
+
*/
|
|
2584
|
+
function listRefTableFor(mode, userId) {
|
|
2585
|
+
if (mode === "single") return "_00_list_ref";
|
|
2586
|
+
const uid = sanitizeUserId(userId);
|
|
2587
|
+
return uid ? `_00_list_ref_user_${uid}` : "_00_list_ref";
|
|
2588
|
+
}
|
|
2589
|
+
|
|
1806
2590
|
//#endregion
|
|
1807
2591
|
//#region src/modules/sync/sync.ts
|
|
1808
2592
|
/**
|
|
1809
|
-
* The main synchronization engine for
|
|
2593
|
+
* The main synchronization engine for Sp00ky.
|
|
1810
2594
|
* Handles the bidirectional synchronization between the local database and the remote backend.
|
|
1811
2595
|
* Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
|
|
1812
2596
|
* @template S The schema structure type.
|
|
1813
2597
|
*/
|
|
1814
|
-
var
|
|
1815
|
-
clientId = "";
|
|
2598
|
+
var Sp00kySync = class {
|
|
1816
2599
|
upQueue;
|
|
1817
2600
|
downQueue;
|
|
1818
2601
|
isInit = false;
|
|
1819
2602
|
logger;
|
|
1820
2603
|
syncEngine;
|
|
2604
|
+
/** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
|
|
2605
|
+
* from `this.events`, which carries Sp00kySync-level events like
|
|
2606
|
+
* `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
|
|
2607
|
+
get engineEvents() {
|
|
2608
|
+
return this.syncEngine.events;
|
|
2609
|
+
}
|
|
1821
2610
|
scheduler;
|
|
2611
|
+
wasDisconnected = false;
|
|
1822
2612
|
events = createSyncEventSystem();
|
|
2613
|
+
currentUserId = null;
|
|
2614
|
+
refMode = DEFAULT_REF_MODE;
|
|
2615
|
+
currentLiveQueryUuid = null;
|
|
2616
|
+
liveQueryUnsubscribe = null;
|
|
2617
|
+
listRefPollTimer = null;
|
|
2618
|
+
listRefPollRunning = false;
|
|
2619
|
+
refSyncIntervalMs;
|
|
2620
|
+
listRefIdleStreak = 0;
|
|
2621
|
+
stillRemoteStreaks = /* @__PURE__ */ new Map();
|
|
2622
|
+
lastLiveEventAt = null;
|
|
2623
|
+
_liveRetryCount = 0;
|
|
2624
|
+
get liveRetryCount() {
|
|
2625
|
+
return this._liveRetryCount;
|
|
2626
|
+
}
|
|
1823
2627
|
get isSyncing() {
|
|
1824
2628
|
return this.scheduler.isSyncing;
|
|
1825
2629
|
}
|
|
@@ -1834,60 +2638,275 @@ var SpookySync = class {
|
|
|
1834
2638
|
this.upQueue.events.unsubscribe(id2);
|
|
1835
2639
|
};
|
|
1836
2640
|
}
|
|
1837
|
-
constructor(local, remote, cache, dataModule, schema, logger) {
|
|
2641
|
+
constructor(local, remote, cache, dataModule, schema, logger, options) {
|
|
1838
2642
|
this.local = local;
|
|
1839
2643
|
this.remote = remote;
|
|
1840
2644
|
this.cache = cache;
|
|
1841
2645
|
this.dataModule = dataModule;
|
|
1842
2646
|
this.schema = schema;
|
|
1843
|
-
this.logger = logger.child({ service: "
|
|
2647
|
+
this.logger = logger.child({ service: "Sp00kySync" });
|
|
1844
2648
|
this.upQueue = new UpQueue(this.local, this.logger);
|
|
1845
2649
|
this.downQueue = new DownQueue(this.local, this.logger);
|
|
1846
2650
|
this.syncEngine = new SyncEngine(this.remote, this.cache, this.schema, this.logger);
|
|
1847
2651
|
this.scheduler = new SyncScheduler(this.upQueue, this.downQueue, this.processUpEvent.bind(this), this.processDownEvent.bind(this), this.logger, this.handleRollback.bind(this));
|
|
2652
|
+
this.refSyncIntervalMs = resolveListRefPollInterval(options?.refSyncIntervalMs);
|
|
1848
2653
|
}
|
|
1849
2654
|
/**
|
|
1850
2655
|
* Initializes the synchronization system.
|
|
1851
2656
|
* Starts the scheduler and initiates the initial sync cycles.
|
|
1852
|
-
* @param clientId The unique identifier for this client instance.
|
|
1853
2657
|
* @throws Error if already initialized.
|
|
1854
2658
|
*/
|
|
1855
|
-
async init(
|
|
1856
|
-
if (this.isInit) throw new Error("
|
|
1857
|
-
this.clientId = clientId;
|
|
2659
|
+
async init() {
|
|
2660
|
+
if (this.isInit) throw new Error("Sp00kySync is already initialized");
|
|
1858
2661
|
this.isInit = true;
|
|
1859
2662
|
await this.scheduler.init();
|
|
1860
|
-
this.
|
|
2663
|
+
this.subscribeToReconnect();
|
|
1861
2664
|
this.scheduler.syncUp();
|
|
1862
2665
|
this.scheduler.syncDown();
|
|
1863
|
-
|
|
2666
|
+
}
|
|
2667
|
+
/**
|
|
2668
|
+
* Push the authenticated user's record id from the parent client's
|
|
2669
|
+
* auth subscription. Tears down the existing `_00_list_ref` LIVE (if
|
|
2670
|
+
* any) and re-registers it under the new user's dedicated table so
|
|
2671
|
+
* SurrealDB binds the permission rule under the post-flip auth
|
|
2672
|
+
* context. Pass `null` on sign-out.
|
|
2673
|
+
*
|
|
2674
|
+
* The dedicated `_00_list_ref_user_<id>` table is created lazily by
|
|
2675
|
+
* the SSP when the first query registration arrives, which may be
|
|
2676
|
+
* concurrent with this call. We retry the LIVE registration with a
|
|
2677
|
+
* short backoff so a "table not found" race resolves without
|
|
2678
|
+
* surfacing as a permanent auth-loading hang.
|
|
2679
|
+
*/
|
|
2680
|
+
async setCurrentUserId(userId) {
|
|
2681
|
+
if (this.currentUserId === userId) return;
|
|
2682
|
+
this.currentUserId = userId;
|
|
2683
|
+
if (!userId) {
|
|
2684
|
+
await this.killRefLiveQuery();
|
|
2685
|
+
this.stopListRefPoll();
|
|
2686
|
+
return;
|
|
2687
|
+
}
|
|
2688
|
+
this.startListRefPoll();
|
|
2689
|
+
const attemptDelays = [
|
|
2690
|
+
0,
|
|
2691
|
+
250,
|
|
2692
|
+
500,
|
|
2693
|
+
1e3,
|
|
2694
|
+
2e3
|
|
2695
|
+
];
|
|
2696
|
+
for (let i = 0; i < attemptDelays.length; i++) {
|
|
2697
|
+
if (attemptDelays[i] > 0) {
|
|
2698
|
+
this._liveRetryCount++;
|
|
2699
|
+
await new Promise((r) => setTimeout(r, attemptDelays[i]));
|
|
2700
|
+
}
|
|
2701
|
+
try {
|
|
2702
|
+
await this.restartRefLiveQuery();
|
|
2703
|
+
return;
|
|
2704
|
+
} catch (err) {
|
|
2705
|
+
this.logger.debug({
|
|
2706
|
+
err,
|
|
2707
|
+
attempt: i + 1,
|
|
2708
|
+
Category: "sp00ky-client::Sp00kySync::setCurrentUserId"
|
|
2709
|
+
}, "Ref LIVE start failed; relying on periodic poll fallback");
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
startListRefPoll() {
|
|
2714
|
+
if (this.listRefPollRunning) return;
|
|
2715
|
+
this.listRefPollRunning = true;
|
|
2716
|
+
this.logger.debug({
|
|
2717
|
+
intervalMs: this.refSyncIntervalMs,
|
|
2718
|
+
Category: "sp00ky-client::Sp00kySync::startListRefPoll"
|
|
2719
|
+
}, "list_ref poll loop started");
|
|
2720
|
+
const schedule = (delayMs) => {
|
|
2721
|
+
this.listRefPollTimer = setTimeout(async () => {
|
|
2722
|
+
if (!this.listRefPollRunning) return;
|
|
2723
|
+
let changed = false;
|
|
2724
|
+
try {
|
|
2725
|
+
changed = await this.pollListRefForActiveQueries();
|
|
2726
|
+
} finally {
|
|
2727
|
+
if (!this.listRefPollRunning) return;
|
|
2728
|
+
this.listRefIdleStreak = changed ? 0 : this.listRefIdleStreak + 1;
|
|
2729
|
+
schedule(listRefPollDelayMs({
|
|
2730
|
+
idleStreak: this.listRefIdleStreak,
|
|
2731
|
+
baseIntervalMs: this.refSyncIntervalMs
|
|
2732
|
+
}));
|
|
2733
|
+
}
|
|
2734
|
+
}, delayMs);
|
|
2735
|
+
};
|
|
2736
|
+
schedule(this.refSyncIntervalMs);
|
|
2737
|
+
}
|
|
2738
|
+
stopListRefPoll() {
|
|
2739
|
+
this.listRefPollRunning = false;
|
|
2740
|
+
if (this.listRefPollTimer !== null) {
|
|
2741
|
+
clearTimeout(this.listRefPollTimer);
|
|
2742
|
+
this.listRefPollTimer = null;
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
/**
|
|
2746
|
+
* One poll cycle: refetch `_00_list_ref` for every active query. Returns
|
|
2747
|
+
* whether ANY query's remoteArray actually changed — the scheduler uses this
|
|
2748
|
+
* to drive the adaptive idle backoff.
|
|
2749
|
+
*/
|
|
2750
|
+
async pollListRefForActiveQueries() {
|
|
2751
|
+
const hashes = this.dataModule.getActiveQueryHashes();
|
|
2752
|
+
if (hashes.length === 0) return false;
|
|
2753
|
+
let anyChanged = false;
|
|
2754
|
+
for (const hash of hashes) try {
|
|
2755
|
+
if (await this.refetchListRefForQuery(hash)) anyChanged = true;
|
|
2756
|
+
} catch (err) {
|
|
2757
|
+
this.logger.debug({
|
|
2758
|
+
err: err?.message ?? err,
|
|
2759
|
+
hash,
|
|
2760
|
+
Category: "sp00ky-client::Sp00kySync::pollListRefForActiveQueries"
|
|
2761
|
+
}, "Per-query list_ref poll failed");
|
|
2762
|
+
}
|
|
2763
|
+
return anyChanged;
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Pull the upstream list_ref entries for `queryHash`, diff them
|
|
2767
|
+
* against the local `remoteArray` cache, sync any added/updated rows
|
|
2768
|
+
* through the SyncEngine, then persist the new remoteArray. This is
|
|
2769
|
+
* the same shape `createRemoteQuery` does for its initial fetch and
|
|
2770
|
+
* what `handleRemoteListRefChange` does per-LIVE-event — we reuse
|
|
2771
|
+
* it on a timer as a fallback for missed LIVE notifications.
|
|
2772
|
+
*/
|
|
2773
|
+
async refetchListRefForQuery(queryHash) {
|
|
2774
|
+
const queryState = this.dataModule.getQueryByHash(queryHash);
|
|
2775
|
+
if (!queryState) return false;
|
|
2776
|
+
const listRefTbl = this.listRefTable();
|
|
2777
|
+
const [items] = await this.remote.query(buildListRefSelect(listRefTbl), { in: queryState.config.id });
|
|
2778
|
+
if (!Array.isArray(items)) return false;
|
|
2779
|
+
const fresh = items.map((item) => [encodeRecordId(item.out), item.version]);
|
|
2780
|
+
const prevRemote = queryState.config.remoteArray ?? [];
|
|
2781
|
+
const freshIds = new Set(fresh.map(([id]) => id));
|
|
2782
|
+
const removedIds = prevRemote.filter(([id]) => !freshIds.has(id)).map(([id]) => id);
|
|
2783
|
+
const changed = !recordVersionArraysEqual(fresh, queryState.config.remoteArray);
|
|
2784
|
+
if (changed) await this.dataModule.updateQueryRemoteArray(queryHash, fresh);
|
|
2785
|
+
try {
|
|
2786
|
+
await this.syncQuery(queryHash);
|
|
2787
|
+
} catch (err) {
|
|
2788
|
+
this.logger.info({
|
|
2789
|
+
err: err?.message ?? err,
|
|
2790
|
+
queryHash,
|
|
2791
|
+
Category: "sp00ky-client::Sp00kySync::refetchListRefForQuery"
|
|
2792
|
+
}, "syncQuery failed during poll");
|
|
2793
|
+
}
|
|
2794
|
+
await this.syncSubqueryChildren(queryHash).catch((err) => {
|
|
2795
|
+
this.logger.info({
|
|
2796
|
+
err: err?.message ?? err,
|
|
2797
|
+
queryHash,
|
|
2798
|
+
Category: "sp00ky-client::Sp00kySync::refetchListRefForQuery"
|
|
2799
|
+
}, "Subquery child sync failed during poll");
|
|
2800
|
+
});
|
|
2801
|
+
if (removedIds.length > 0) try {
|
|
2802
|
+
await this.dataModule.notifyQuerySynced(queryHash);
|
|
2803
|
+
} catch (err) {
|
|
2804
|
+
this.logger.info({
|
|
2805
|
+
err: err?.message ?? err,
|
|
2806
|
+
queryHash,
|
|
2807
|
+
Category: "sp00ky-client::Sp00kySync::refetchListRefForQuery"
|
|
2808
|
+
}, "notifyQuerySynced failed during poll-removal re-render");
|
|
2809
|
+
}
|
|
2810
|
+
return changed;
|
|
2811
|
+
}
|
|
2812
|
+
/**
|
|
2813
|
+
* Resolve the current `_00_list_ref` table name for the active auth
|
|
2814
|
+
* context. Public so the `createRemoteQuery` initial-fetch path can
|
|
2815
|
+
* read from the right per-user table.
|
|
2816
|
+
*
|
|
2817
|
+
* Reads the user id from `DataModule` rather than the local mirror,
|
|
2818
|
+
* because `DataModule.setCurrentUserId` runs synchronously from the
|
|
2819
|
+
* auth callback (before any `await`), whereas `sync.setCurrentUserId`
|
|
2820
|
+
* is async — the userQuery's initial fetch can fire between those
|
|
2821
|
+
* two points and we need the correct table name immediately.
|
|
2822
|
+
*/
|
|
2823
|
+
listRefTable() {
|
|
2824
|
+
return listRefTableFor(this.refMode, this.dataModule.getCurrentUserId());
|
|
2825
|
+
}
|
|
2826
|
+
async killRefLiveQuery() {
|
|
2827
|
+
if (this.liveQueryUnsubscribe) {
|
|
2828
|
+
try {
|
|
2829
|
+
this.liveQueryUnsubscribe();
|
|
2830
|
+
} catch {}
|
|
2831
|
+
this.liveQueryUnsubscribe = null;
|
|
2832
|
+
}
|
|
2833
|
+
if (this.currentLiveQueryUuid !== null) {
|
|
2834
|
+
try {
|
|
2835
|
+
await this.remote.query("KILL $u", { u: this.currentLiveQueryUuid });
|
|
2836
|
+
} catch (err) {
|
|
2837
|
+
this.logger.debug({
|
|
2838
|
+
err,
|
|
2839
|
+
Category: "sp00ky-client::Sp00kySync::killRefLiveQuery"
|
|
2840
|
+
}, "Prior LIVE KILL failed; continuing");
|
|
2841
|
+
}
|
|
2842
|
+
this.currentLiveQueryUuid = null;
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
async restartRefLiveQuery() {
|
|
2846
|
+
await this.killRefLiveQuery();
|
|
2847
|
+
await this.startRefLiveQueries();
|
|
2848
|
+
}
|
|
2849
|
+
subscribeToReconnect() {
|
|
2850
|
+
const client = this.remote.getClient();
|
|
2851
|
+
client.subscribe("disconnected", () => {
|
|
2852
|
+
this.wasDisconnected = true;
|
|
2853
|
+
this.logger.info({ Category: "sp00ky-client::Sp00kySync::onDisconnect" }, "Remote disconnected");
|
|
2854
|
+
});
|
|
2855
|
+
client.subscribe("connected", () => {
|
|
2856
|
+
if (!this.wasDisconnected) return;
|
|
2857
|
+
this.wasDisconnected = false;
|
|
2858
|
+
this.logger.info({ Category: "sp00ky-client::Sp00kySync::onReconnect" }, "Remote reconnected, refetching active queries");
|
|
2859
|
+
for (const hash of this.dataModule.getActiveQueryHashes()) this.scheduler.enqueueDownEvent({
|
|
2860
|
+
type: "register",
|
|
2861
|
+
payload: { hash }
|
|
2862
|
+
});
|
|
2863
|
+
if (this.currentUserId) this.restartRefLiveQuery().catch((err) => {
|
|
2864
|
+
this.logger.debug({
|
|
2865
|
+
err,
|
|
2866
|
+
Category: "sp00ky-client::Sp00kySync::onReconnect"
|
|
2867
|
+
}, "LIVE restart after reconnect failed; relying on poll fallback");
|
|
2868
|
+
});
|
|
2869
|
+
});
|
|
1864
2870
|
}
|
|
1865
2871
|
async startRefLiveQueries() {
|
|
2872
|
+
const tableName = this.listRefTable();
|
|
1866
2873
|
this.logger.debug({
|
|
1867
|
-
|
|
1868
|
-
Category: "
|
|
2874
|
+
tableName,
|
|
2875
|
+
Category: "sp00ky-client::Sp00kySync::startRefLiveQueries"
|
|
1869
2876
|
}, "Starting ref live queries");
|
|
1870
|
-
const [queryUuid] = await this.remote.query(
|
|
1871
|
-
|
|
2877
|
+
const [queryUuid] = await this.remote.query(`LIVE SELECT * FROM ${tableName}`);
|
|
2878
|
+
this.currentLiveQueryUuid = queryUuid;
|
|
2879
|
+
this.liveQueryUnsubscribe = (await this.remote.getClient().liveOf(queryUuid)).subscribe((message) => {
|
|
1872
2880
|
this.logger.debug({
|
|
1873
2881
|
message,
|
|
1874
|
-
Category: "
|
|
2882
|
+
Category: "sp00ky-client::Sp00kySync::startRefLiveQueries"
|
|
1875
2883
|
}, "Live update received");
|
|
1876
2884
|
if (message.action === "KILLED") return;
|
|
2885
|
+
if (message.value.parent != null) {
|
|
2886
|
+
this.handleRemoteSubqueryChange(message.action, message.value.in, message.value.out, message.value.version).catch((err) => {
|
|
2887
|
+
this.logger.error({
|
|
2888
|
+
err,
|
|
2889
|
+
Category: "sp00ky-client::Sp00kySync::startRefLiveQueries"
|
|
2890
|
+
}, "Error handling remote subquery change");
|
|
2891
|
+
});
|
|
2892
|
+
return;
|
|
2893
|
+
}
|
|
1877
2894
|
this.handleRemoteListRefChange(message.action, message.value.in, message.value.out, message.value.version).catch((err) => {
|
|
1878
2895
|
this.logger.error({
|
|
1879
2896
|
err,
|
|
1880
|
-
Category: "
|
|
2897
|
+
Category: "sp00ky-client::Sp00kySync::startRefLiveQueries"
|
|
1881
2898
|
}, "Error handling remote list ref change");
|
|
1882
2899
|
});
|
|
1883
2900
|
});
|
|
1884
2901
|
}
|
|
1885
2902
|
async handleRemoteListRefChange(action, queryId, recordId, version) {
|
|
2903
|
+
this.lastLiveEventAt = Date.now();
|
|
2904
|
+
this.listRefIdleStreak = 0;
|
|
1886
2905
|
const existing = this.dataModule.getQueryById(queryId);
|
|
1887
2906
|
if (!existing) {
|
|
1888
2907
|
this.logger.warn({
|
|
1889
2908
|
queryId: queryId.toString(),
|
|
1890
|
-
Category: "
|
|
2909
|
+
Category: "sp00ky-client::Sp00kySync::handleRemoteListRefChange"
|
|
1891
2910
|
}, "Received remote update for unknown local query");
|
|
1892
2911
|
return;
|
|
1893
2912
|
}
|
|
@@ -1898,10 +2917,46 @@ var SpookySync = class {
|
|
|
1898
2917
|
recordId,
|
|
1899
2918
|
version,
|
|
1900
2919
|
localArray,
|
|
1901
|
-
Category: "
|
|
2920
|
+
Category: "sp00ky-client::Sp00kySync::handleRemoteListRefChange"
|
|
1902
2921
|
}, "Live update is being processed");
|
|
1903
2922
|
const diff = createDiffFromDbOp(action, recordId, version, localArray);
|
|
1904
|
-
|
|
2923
|
+
const hash = extractIdPart(existing.config.id);
|
|
2924
|
+
await this.runSyncForQuery(hash, diff);
|
|
2925
|
+
}
|
|
2926
|
+
/**
|
|
2927
|
+
* Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
|
|
2928
|
+
* `parent` set) for a `.related()` query. Unlike primary rows, child rows
|
|
2929
|
+
* must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
|
|
2930
|
+
* keep the child BODY fresh in the local cache so the in-browser SSP's
|
|
2931
|
+
* subquery-table dependency re-materializes the parent view.
|
|
2932
|
+
*
|
|
2933
|
+
* CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
|
|
2934
|
+
* no-op: a child leaving this query's set must not delete a body another
|
|
2935
|
+
* query may still show (see `syncSubqueryChildren` deletion-safety note);
|
|
2936
|
+
* a genuine record delete propagates via the normal delete path.
|
|
2937
|
+
*/
|
|
2938
|
+
async handleRemoteSubqueryChange(action, queryId, childId, version) {
|
|
2939
|
+
this.lastLiveEventAt = Date.now();
|
|
2940
|
+
this.listRefIdleStreak = 0;
|
|
2941
|
+
if (action === "DELETE") return;
|
|
2942
|
+
const existing = this.dataModule.getQueryById(queryId);
|
|
2943
|
+
if (!existing) return;
|
|
2944
|
+
const item = {
|
|
2945
|
+
id: childId,
|
|
2946
|
+
version
|
|
2947
|
+
};
|
|
2948
|
+
await this.syncEngine.syncRecords(action === "CREATE" ? {
|
|
2949
|
+
added: [item],
|
|
2950
|
+
updated: [],
|
|
2951
|
+
removed: []
|
|
2952
|
+
} : {
|
|
2953
|
+
added: [],
|
|
2954
|
+
updated: [item],
|
|
2955
|
+
removed: []
|
|
2956
|
+
});
|
|
2957
|
+
const key = encodeRecordId(childId);
|
|
2958
|
+
const prev = existing.config.subqueryRemoteArray ?? [];
|
|
2959
|
+
existing.config.subqueryRemoteArray = [...prev.filter(([id]) => id !== key), [key, version]];
|
|
1905
2960
|
}
|
|
1906
2961
|
/**
|
|
1907
2962
|
* Enqueues a 'down' event (from remote to local) for processing.
|
|
@@ -1913,11 +2968,10 @@ var SpookySync = class {
|
|
|
1913
2968
|
async processUpEvent(event) {
|
|
1914
2969
|
this.logger.debug({
|
|
1915
2970
|
event,
|
|
1916
|
-
Category: "
|
|
2971
|
+
Category: "sp00ky-client::Sp00kySync::processUpEvent"
|
|
1917
2972
|
}, "Processing up event");
|
|
1918
|
-
console.log("xx1", event);
|
|
1919
2973
|
switch (event.type) {
|
|
1920
|
-
case "create":
|
|
2974
|
+
case "create": {
|
|
1921
2975
|
const dataKeys = Object.keys(event.data).map((key) => ({
|
|
1922
2976
|
key,
|
|
1923
2977
|
variable: `data_${key}`
|
|
@@ -1929,6 +2983,7 @@ var SpookySync = class {
|
|
|
1929
2983
|
...prefixedParams
|
|
1930
2984
|
});
|
|
1931
2985
|
break;
|
|
2986
|
+
}
|
|
1932
2987
|
case "update":
|
|
1933
2988
|
await this.remote.query(`UPDATE $id MERGE $data`, {
|
|
1934
2989
|
id: event.record_id,
|
|
@@ -1941,7 +2996,7 @@ var SpookySync = class {
|
|
|
1941
2996
|
default:
|
|
1942
2997
|
this.logger.error({
|
|
1943
2998
|
event,
|
|
1944
|
-
Category: "
|
|
2999
|
+
Category: "sp00ky-client::Sp00kySync::processUpEvent"
|
|
1945
3000
|
}, "processUpEvent unknown event type");
|
|
1946
3001
|
return;
|
|
1947
3002
|
}
|
|
@@ -1954,7 +3009,7 @@ var SpookySync = class {
|
|
|
1954
3009
|
recordId,
|
|
1955
3010
|
tableName,
|
|
1956
3011
|
error: error.message,
|
|
1957
|
-
Category: "
|
|
3012
|
+
Category: "sp00ky-client::Sp00kySync::handleRollback"
|
|
1958
3013
|
}, "Rolling back failed mutation");
|
|
1959
3014
|
switch (event.type) {
|
|
1960
3015
|
case "create":
|
|
@@ -1964,13 +3019,13 @@ var SpookySync = class {
|
|
|
1964
3019
|
if (event.beforeRecord) await this.dataModule.rollbackUpdate(event.record_id, tableName, event.beforeRecord);
|
|
1965
3020
|
else this.logger.warn({
|
|
1966
3021
|
recordId,
|
|
1967
|
-
Category: "
|
|
3022
|
+
Category: "sp00ky-client::Sp00kySync::handleRollback"
|
|
1968
3023
|
}, "Cannot rollback update: no beforeRecord available. Down-sync will reconcile.");
|
|
1969
3024
|
break;
|
|
1970
3025
|
case "delete":
|
|
1971
3026
|
this.logger.warn({
|
|
1972
3027
|
recordId,
|
|
1973
|
-
Category: "
|
|
3028
|
+
Category: "sp00ky-client::Sp00kySync::handleRollback"
|
|
1974
3029
|
}, "Delete rollback not implemented. Down-sync will reconcile.");
|
|
1975
3030
|
break;
|
|
1976
3031
|
}
|
|
@@ -1983,7 +3038,7 @@ var SpookySync = class {
|
|
|
1983
3038
|
async processDownEvent(event) {
|
|
1984
3039
|
this.logger.debug({
|
|
1985
3040
|
event,
|
|
1986
|
-
Category: "
|
|
3041
|
+
Category: "sp00ky-client::Sp00kySync::processDownEvent"
|
|
1987
3042
|
}, "Processing down event");
|
|
1988
3043
|
switch (event.type) {
|
|
1989
3044
|
case "register": return this.registerQuery(event.payload.hash);
|
|
@@ -2002,13 +3057,76 @@ var SpookySync = class {
|
|
|
2002
3057
|
if (!queryState) {
|
|
2003
3058
|
this.logger.warn({
|
|
2004
3059
|
hash,
|
|
2005
|
-
Category: "
|
|
3060
|
+
Category: "sp00ky-client::Sp00kySync::syncQuery"
|
|
2006
3061
|
}, "Query not found");
|
|
2007
3062
|
return;
|
|
2008
3063
|
}
|
|
2009
3064
|
const diff = new ArraySyncer(queryState.config.localArray, queryState.config.remoteArray).nextSet();
|
|
2010
3065
|
if (!diff) return;
|
|
2011
|
-
return this.
|
|
3066
|
+
return this.runSyncForQuery(hash, diff);
|
|
3067
|
+
}
|
|
3068
|
+
/**
|
|
3069
|
+
* Run a sync for a single query while reflecting its fetch status. Marks the
|
|
3070
|
+
* query `fetching` for the duration when the diff actually pulls records
|
|
3071
|
+
* (added/updated), then resets to `idle` in a `finally` so a failed sync
|
|
3072
|
+
* never leaves a query stuck `fetching`. Part A's notification coalescing
|
|
3073
|
+
* means the single resulting UI update lands after this completes.
|
|
3074
|
+
*/
|
|
3075
|
+
async runSyncForQuery(hash, diff) {
|
|
3076
|
+
if (diff.added.length > 0 || diff.updated.length > 0) {
|
|
3077
|
+
const pendingDeletes = await this.getPendingDeleteIds();
|
|
3078
|
+
if (pendingDeletes.size > 0) diff = {
|
|
3079
|
+
added: diff.added.filter((r) => !pendingDeletes.has(encodeRecordId(r.id))),
|
|
3080
|
+
updated: diff.updated.filter((r) => !pendingDeletes.has(encodeRecordId(r.id))),
|
|
3081
|
+
removed: diff.removed
|
|
3082
|
+
};
|
|
3083
|
+
}
|
|
3084
|
+
const fetching = diff.added.length + diff.updated.length > 0;
|
|
3085
|
+
if (fetching) this.dataModule.setQueryStatus(hash, "fetching");
|
|
3086
|
+
try {
|
|
3087
|
+
const { remoteFetchMs, stillRemoteIds } = await this.syncEngine.syncRecords(diff);
|
|
3088
|
+
if (fetching) this.dataModule.recordRemoteFetch(hash, remoteFetchMs);
|
|
3089
|
+
if (stillRemoteIds.length > 0) {
|
|
3090
|
+
const CONVERGE_AFTER = 3;
|
|
3091
|
+
const toConverge = [];
|
|
3092
|
+
for (const id of stillRemoteIds) {
|
|
3093
|
+
const key = `${hash}:${id}`;
|
|
3094
|
+
const n = (this.stillRemoteStreaks.get(key) ?? 0) + 1;
|
|
3095
|
+
if (n >= CONVERGE_AFTER) {
|
|
3096
|
+
this.stillRemoteStreaks.delete(key);
|
|
3097
|
+
toConverge.push(id);
|
|
3098
|
+
} else this.stillRemoteStreaks.set(key, n);
|
|
3099
|
+
}
|
|
3100
|
+
if (toConverge.length > 0) {
|
|
3101
|
+
const local = this.dataModule.getQueryByHash(hash)?.config.localArray;
|
|
3102
|
+
if (local && local.length > 0) {
|
|
3103
|
+
const drop = new Set(toConverge);
|
|
3104
|
+
const next = local.filter(([id]) => !drop.has(id));
|
|
3105
|
+
if (next.length !== local.length) await this.dataModule.updateQueryLocalArray(hash, next);
|
|
3106
|
+
}
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
} finally {
|
|
3110
|
+
if (fetching) this.dataModule.setQueryStatus(hash, "idle");
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
|
|
3115
|
+
* Sync must not re-fetch/re-insert these — the remote delete is async, so the
|
|
3116
|
+
* server's `_00_list_ref` still lists them until it's processed, and the diff
|
|
3117
|
+
* would otherwise resurrect a just-deleted record.
|
|
3118
|
+
*/
|
|
3119
|
+
async getPendingDeleteIds() {
|
|
3120
|
+
try {
|
|
3121
|
+
const [rows] = await this.local.query("SELECT recordId FROM _00_pending_mutations WHERE mutationType = 'delete'");
|
|
3122
|
+
return new Set((rows ?? []).map((r) => encodeRecordId(r.recordId)));
|
|
3123
|
+
} catch (err) {
|
|
3124
|
+
this.logger.warn({
|
|
3125
|
+
err,
|
|
3126
|
+
Category: "sp00ky-client::Sp00kySync::getPendingDeleteIds"
|
|
3127
|
+
}, "Failed to read pending deletes; sync may briefly resurrect a just-deleted record");
|
|
3128
|
+
return /* @__PURE__ */ new Set();
|
|
3129
|
+
}
|
|
2012
3130
|
}
|
|
2013
3131
|
/**
|
|
2014
3132
|
* Enqueues a list of mutations (up events) to be sent to the remote.
|
|
@@ -2021,7 +3139,7 @@ var SpookySync = class {
|
|
|
2021
3139
|
try {
|
|
2022
3140
|
this.logger.debug({
|
|
2023
3141
|
queryHash,
|
|
2024
|
-
Category: "
|
|
3142
|
+
Category: "sp00ky-client::Sp00kySync::registerQuery"
|
|
2025
3143
|
}, "Register Query state");
|
|
2026
3144
|
await this.createRemoteQuery(queryHash);
|
|
2027
3145
|
await this.syncQuery(queryHash);
|
|
@@ -2029,7 +3147,7 @@ var SpookySync = class {
|
|
|
2029
3147
|
} catch (e) {
|
|
2030
3148
|
this.logger.error({
|
|
2031
3149
|
err: e,
|
|
2032
|
-
Category: "
|
|
3150
|
+
Category: "sp00ky-client::Sp00kySync::registerQuery"
|
|
2033
3151
|
}, "registerQuery error");
|
|
2034
3152
|
throw e;
|
|
2035
3153
|
}
|
|
@@ -2039,37 +3157,80 @@ var SpookySync = class {
|
|
|
2039
3157
|
if (!queryState) {
|
|
2040
3158
|
this.logger.warn({
|
|
2041
3159
|
queryHash,
|
|
2042
|
-
Category: "
|
|
3160
|
+
Category: "sp00ky-client::Sp00kySync::createRemoteQuery"
|
|
2043
3161
|
}, "Query to register not found");
|
|
2044
3162
|
throw new Error("Query to register not found");
|
|
2045
3163
|
}
|
|
2046
3164
|
await this.remote.query("fn::query::register($config)", { config: {
|
|
2047
|
-
clientId: this.clientId,
|
|
2048
3165
|
id: queryState.config.id,
|
|
2049
3166
|
surql: queryState.config.surql,
|
|
2050
3167
|
params: queryState.config.params,
|
|
2051
3168
|
ttl: queryState.config.ttl
|
|
2052
3169
|
} });
|
|
2053
|
-
const
|
|
3170
|
+
const listRefTbl = this.listRefTable();
|
|
3171
|
+
const [items] = await this.remote.query(buildListRefSelect(listRefTbl), { in: queryState.config.id });
|
|
2054
3172
|
this.logger.trace({
|
|
2055
3173
|
queryId: encodeRecordId(queryState.config.id),
|
|
2056
3174
|
items,
|
|
2057
|
-
Category: "
|
|
3175
|
+
Category: "sp00ky-client::Sp00kySync::createRemoteQuery"
|
|
2058
3176
|
}, "Got query record version array from remote");
|
|
2059
3177
|
const array = items.map((item) => [encodeRecordId(item.out), item.version]);
|
|
2060
3178
|
this.logger.debug({
|
|
2061
3179
|
queryId: encodeRecordId(queryState.config.id),
|
|
2062
3180
|
array,
|
|
2063
|
-
Category: "
|
|
3181
|
+
Category: "sp00ky-client::Sp00kySync::createRemoteQuery"
|
|
2064
3182
|
}, "createdRemoteQuery");
|
|
2065
3183
|
if (array) await this.dataModule.updateQueryRemoteArray(queryHash, array);
|
|
3184
|
+
await this.syncSubqueryChildren(queryHash).catch((err) => {
|
|
3185
|
+
this.logger.info({
|
|
3186
|
+
err: err?.message ?? err,
|
|
3187
|
+
queryHash,
|
|
3188
|
+
Category: "sp00ky-client::Sp00kySync::createRemoteQuery"
|
|
3189
|
+
}, "Subquery child sync failed during registration; poll will retry");
|
|
3190
|
+
});
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Sync the BODIES of a `.related()` query's subquery child rows into the
|
|
3194
|
+
* local cache, separately from the primary window array. The SSP writes
|
|
3195
|
+
* each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
|
|
3196
|
+
* `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
|
|
3197
|
+
* nesting depth). We diff against the in-memory `subqueryRemoteArray` and
|
|
3198
|
+
* fetch added/updated bodies through the SyncEngine — which `saveBatch`s
|
|
3199
|
+
* them into the local DB AND the in-browser SSP, whose subquery-table
|
|
3200
|
+
* dependency then re-materializes the parent view (no explicit notify).
|
|
3201
|
+
*
|
|
3202
|
+
* Deletion safety: we pass `removed: []` deliberately. A child body can be
|
|
3203
|
+
* shared by other queries; letting `handleRemovedRecords` delete one that
|
|
3204
|
+
* merely left THIS query's child set would clobber data another query still
|
|
3205
|
+
* shows. Genuine record deletes flow through the normal delete path; a
|
|
3206
|
+
* lingering orphan body is invisible (the correlated WHERE stops matching).
|
|
3207
|
+
*
|
|
3208
|
+
* Kept off `runSyncForQuery` on purpose so child fetches never flip the
|
|
3209
|
+
* query to `fetching` or skew its DevTools timings.
|
|
3210
|
+
*/
|
|
3211
|
+
async syncSubqueryChildren(queryHash) {
|
|
3212
|
+
const queryState = this.dataModule.getQueryByHash(queryHash);
|
|
3213
|
+
if (!queryState) return;
|
|
3214
|
+
const listRefTbl = this.listRefTable();
|
|
3215
|
+
const [items] = await this.remote.query(buildSubqueryListRefSelect(listRefTbl), { in: queryState.config.id });
|
|
3216
|
+
if (!Array.isArray(items)) return;
|
|
3217
|
+
const fresh = items.map((item) => [encodeRecordId(item.out), item.version]);
|
|
3218
|
+
const prev = queryState.config.subqueryRemoteArray ?? [];
|
|
3219
|
+
if (recordVersionArraysEqual(fresh, prev)) return;
|
|
3220
|
+
const diff = diffRecordVersionArray(prev, fresh);
|
|
3221
|
+
if (diff.added.length > 0 || diff.updated.length > 0) await this.syncEngine.syncRecords({
|
|
3222
|
+
added: diff.added,
|
|
3223
|
+
updated: diff.updated,
|
|
3224
|
+
removed: []
|
|
3225
|
+
});
|
|
3226
|
+
queryState.config.subqueryRemoteArray = fresh;
|
|
2066
3227
|
}
|
|
2067
3228
|
async heartbeatQuery(queryHash) {
|
|
2068
3229
|
const queryState = this.dataModule.getQueryByHash(queryHash);
|
|
2069
3230
|
if (!queryState) {
|
|
2070
3231
|
this.logger.warn({
|
|
2071
3232
|
queryHash,
|
|
2072
|
-
Category: "
|
|
3233
|
+
Category: "sp00ky-client::Sp00kySync::heartbeatQuery"
|
|
2073
3234
|
}, "Query to register not found");
|
|
2074
3235
|
throw new Error("Query to register not found");
|
|
2075
3236
|
}
|
|
@@ -2077,14 +3238,17 @@ var SpookySync = class {
|
|
|
2077
3238
|
}
|
|
2078
3239
|
async cleanupQuery(queryHash) {
|
|
2079
3240
|
const queryState = this.dataModule.getQueryByHash(queryHash);
|
|
2080
|
-
if (!queryState)
|
|
2081
|
-
|
|
2082
|
-
queryHash,
|
|
2083
|
-
Category: "spooky-client::SpookySync::cleanupQuery"
|
|
2084
|
-
}, "Query to register not found");
|
|
2085
|
-
throw new Error("Query to register not found");
|
|
2086
|
-
}
|
|
3241
|
+
if (!queryState) return;
|
|
3242
|
+
if (this.dataModule.hasSubscribers(queryHash)) return;
|
|
2087
3243
|
await this.remote.query(`DELETE $id`, { id: queryState.config.id });
|
|
3244
|
+
if (this.dataModule.hasSubscribers(queryHash)) {
|
|
3245
|
+
this.enqueueDownEvent({
|
|
3246
|
+
type: "register",
|
|
3247
|
+
payload: { hash: queryHash }
|
|
3248
|
+
});
|
|
3249
|
+
return;
|
|
3250
|
+
}
|
|
3251
|
+
this.dataModule.finalizeDeregister(queryHash);
|
|
2088
3252
|
}
|
|
2089
3253
|
};
|
|
2090
3254
|
|
|
@@ -2095,12 +3259,67 @@ function createAuthEventSystem() {
|
|
|
2095
3259
|
return createEventSystem([AuthEventTypes.AuthStateChanged]);
|
|
2096
3260
|
}
|
|
2097
3261
|
|
|
3262
|
+
//#endregion
|
|
3263
|
+
//#region src/modules/devtools/versions.ts
|
|
3264
|
+
const UNAVAILABLE = "unavailable";
|
|
3265
|
+
function emptyBackendVersions() {
|
|
3266
|
+
return {
|
|
3267
|
+
ssp: UNAVAILABLE,
|
|
3268
|
+
scheduler: UNAVAILABLE,
|
|
3269
|
+
surrealdb: UNAVAILABLE
|
|
3270
|
+
};
|
|
3271
|
+
}
|
|
3272
|
+
function emptyBackendInfo() {
|
|
3273
|
+
return {
|
|
3274
|
+
versions: emptyBackendVersions(),
|
|
3275
|
+
entities: []
|
|
3276
|
+
};
|
|
3277
|
+
}
|
|
3278
|
+
/** Strip a leading `surrealdb-` so versions read as bare semver (e.g. `2.0.3`). */
|
|
3279
|
+
function normalizeServerVersion(v) {
|
|
3280
|
+
return String(v).replace(/^surrealdb-/i, "").trim();
|
|
3281
|
+
}
|
|
3282
|
+
/**
|
|
3283
|
+
* Normalize whatever `RETURN fn::spooky::info()` resolves to into the entity
|
|
3284
|
+
* array. The SurrealQL function returns the parsed `/info` array; depending on
|
|
3285
|
+
* how the result is unwrapped it may arrive as the array itself, a single
|
|
3286
|
+
* object, or `null`. Tolerant of all three.
|
|
3287
|
+
*/
|
|
3288
|
+
function toEntityArray(raw) {
|
|
3289
|
+
if (Array.isArray(raw)) return raw.filter((e) => !!e && typeof e === "object");
|
|
3290
|
+
if (raw && typeof raw === "object") return [raw];
|
|
3291
|
+
return [];
|
|
3292
|
+
}
|
|
3293
|
+
/**
|
|
3294
|
+
* Derive component versions + the full entity list from a `/info` entity array.
|
|
3295
|
+
* `surrealdb` is taken from whichever entity reports `surrealdb_version` (ssp or
|
|
3296
|
+
* scheduler). Never throws; missing pieces stay `'unavailable'`.
|
|
3297
|
+
*/
|
|
3298
|
+
function parseBackendInfo(raw) {
|
|
3299
|
+
const entities = toEntityArray(raw);
|
|
3300
|
+
const versions = emptyBackendVersions();
|
|
3301
|
+
for (const entity of entities) {
|
|
3302
|
+
const version = entity.version ? String(entity.version) : void 0;
|
|
3303
|
+
if (entity.entity === "ssp" && version) versions.ssp = version;
|
|
3304
|
+
else if (entity.entity === "scheduler" && version) versions.scheduler = version;
|
|
3305
|
+
if (versions.surrealdb === UNAVAILABLE && entity.surrealdb_version) versions.surrealdb = normalizeServerVersion(String(entity.surrealdb_version));
|
|
3306
|
+
}
|
|
3307
|
+
return {
|
|
3308
|
+
versions,
|
|
3309
|
+
entities
|
|
3310
|
+
};
|
|
3311
|
+
}
|
|
3312
|
+
|
|
2098
3313
|
//#endregion
|
|
2099
3314
|
//#region src/modules/devtools/index.ts
|
|
3315
|
+
const CORE_VERSION = "0.0.1-canary.81";
|
|
3316
|
+
const WASM_VERSION = "0.0.1-canary.81";
|
|
3317
|
+
const SURREAL_VERSION = "3.0.3";
|
|
2100
3318
|
var DevToolsService = class {
|
|
2101
3319
|
eventsHistory = [];
|
|
2102
3320
|
eventIdCounter = 0;
|
|
2103
|
-
version =
|
|
3321
|
+
version = CORE_VERSION;
|
|
3322
|
+
backendInfo = emptyBackendInfo();
|
|
2104
3323
|
constructor(databaseService, remoteDatabaseService, logger, schema, authService, dataManager) {
|
|
2105
3324
|
this.databaseService = databaseService;
|
|
2106
3325
|
this.remoteDatabaseService = remoteDatabaseService;
|
|
@@ -2112,7 +3331,26 @@ var DevToolsService = class {
|
|
|
2112
3331
|
this.authService.eventSystem.subscribe(AuthEventTypes.AuthStateChanged, () => {
|
|
2113
3332
|
this.notifyDevTools();
|
|
2114
3333
|
});
|
|
2115
|
-
this.
|
|
3334
|
+
this.refreshBackendVersions();
|
|
3335
|
+
this.logger.debug({ Category: "sp00ky-client::DevToolsService::init" }, "Service initialized");
|
|
3336
|
+
}
|
|
3337
|
+
/**
|
|
3338
|
+
* Re-read backend stack info via the `fn::spooky::info()` SurrealQL function
|
|
3339
|
+
* over the open remote connection (no HTTP/CORS), then notify the panel.
|
|
3340
|
+
* Never throws: on failure the info stays empty/'unavailable'.
|
|
3341
|
+
*/
|
|
3342
|
+
async refreshBackendVersions() {
|
|
3343
|
+
try {
|
|
3344
|
+
const result = await this.remoteDatabaseService.query("RETURN fn::spooky::info()");
|
|
3345
|
+
this.backendInfo = parseBackendInfo(Array.isArray(result) ? result[0] : result);
|
|
3346
|
+
} catch (err) {
|
|
3347
|
+
this.logger.debug({
|
|
3348
|
+
err,
|
|
3349
|
+
Category: "sp00ky-client::DevToolsService::versions"
|
|
3350
|
+
}, "fn::spooky::info() unavailable; backend versions stay unavailable");
|
|
3351
|
+
this.backendInfo = emptyBackendInfo();
|
|
3352
|
+
}
|
|
3353
|
+
this.notifyDevTools();
|
|
2116
3354
|
}
|
|
2117
3355
|
getActiveQueries() {
|
|
2118
3356
|
const result = /* @__PURE__ */ new Map();
|
|
@@ -2122,6 +3360,8 @@ var DevToolsService = class {
|
|
|
2122
3360
|
result.set(queryHash, {
|
|
2123
3361
|
queryHash,
|
|
2124
3362
|
status: "active",
|
|
3363
|
+
fetchStatus: q.status,
|
|
3364
|
+
isFetching: q.status === "fetching",
|
|
2125
3365
|
createdAt: q.config.lastActiveAt instanceof Date ? q.config.lastActiveAt.getTime() : new Date(q.config.lastActiveAt || Date.now()).getTime(),
|
|
2126
3366
|
lastUpdate: Date.now(),
|
|
2127
3367
|
updateCount: q.updateCount,
|
|
@@ -2130,7 +3370,8 @@ var DevToolsService = class {
|
|
|
2130
3370
|
dataSize: q.records?.length || 0,
|
|
2131
3371
|
data: q.records,
|
|
2132
3372
|
localArray: q.config.localArray,
|
|
2133
|
-
remoteArray: q.config.remoteArray
|
|
3373
|
+
remoteArray: q.config.remoteArray,
|
|
3374
|
+
timings: this.dataManager.phaseTimings(q)
|
|
2134
3375
|
});
|
|
2135
3376
|
});
|
|
2136
3377
|
return result;
|
|
@@ -2138,7 +3379,7 @@ var DevToolsService = class {
|
|
|
2138
3379
|
onQueryInitialized(payload) {
|
|
2139
3380
|
this.logger.debug({
|
|
2140
3381
|
payload,
|
|
2141
|
-
Category: "
|
|
3382
|
+
Category: "sp00ky-client::DevToolsService::onQueryInitialized"
|
|
2142
3383
|
}, "QueryInitialized");
|
|
2143
3384
|
const queryHash = this.hashString(payload.queryId.toString());
|
|
2144
3385
|
this.addEvent("QUERY_REQUEST_INIT", {
|
|
@@ -2151,7 +3392,7 @@ var DevToolsService = class {
|
|
|
2151
3392
|
onQueryUpdated(payload) {
|
|
2152
3393
|
this.logger.debug({
|
|
2153
3394
|
id: payload.queryId?.toString(),
|
|
2154
|
-
Category: "
|
|
3395
|
+
Category: "sp00ky-client::DevToolsService::onQueryUpdated"
|
|
2155
3396
|
}, "QueryUpdated");
|
|
2156
3397
|
const queryHash = this.hashString(payload.queryId.toString());
|
|
2157
3398
|
this.addEvent("QUERY_UPDATED", {
|
|
@@ -2163,7 +3404,7 @@ var DevToolsService = class {
|
|
|
2163
3404
|
onStreamUpdate(update) {
|
|
2164
3405
|
this.logger.debug({
|
|
2165
3406
|
update,
|
|
2166
|
-
Category: "
|
|
3407
|
+
Category: "sp00ky-client::DevToolsService::onStreamUpdate"
|
|
2167
3408
|
}, "StreamUpdate");
|
|
2168
3409
|
this.addEvent("STREAM_UPDATE", { updates: [update] });
|
|
2169
3410
|
this.notifyDevTools();
|
|
@@ -2210,6 +3451,15 @@ var DevToolsService = class {
|
|
|
2210
3451
|
userId: this.authService.currentUser?.id
|
|
2211
3452
|
},
|
|
2212
3453
|
version: this.version,
|
|
3454
|
+
versions: {
|
|
3455
|
+
frontend: {
|
|
3456
|
+
core: CORE_VERSION,
|
|
3457
|
+
wasm: WASM_VERSION,
|
|
3458
|
+
surrealdb: SURREAL_VERSION
|
|
3459
|
+
},
|
|
3460
|
+
backend: this.backendInfo.versions,
|
|
3461
|
+
entities: this.backendInfo.entities
|
|
3462
|
+
},
|
|
2213
3463
|
database: {
|
|
2214
3464
|
tables: this.schema.tables.map((t) => t.name),
|
|
2215
3465
|
tableData: {}
|
|
@@ -2218,8 +3468,8 @@ var DevToolsService = class {
|
|
|
2218
3468
|
}
|
|
2219
3469
|
notifyDevTools() {
|
|
2220
3470
|
if (typeof window !== "undefined") window.postMessage({
|
|
2221
|
-
type: "
|
|
2222
|
-
source: "
|
|
3471
|
+
type: "SP00KY_STATE_CHANGED",
|
|
3472
|
+
source: "sp00ky-devtools-page",
|
|
2223
3473
|
state: this.getState()
|
|
2224
3474
|
}, "*");
|
|
2225
3475
|
}
|
|
@@ -2245,13 +3495,14 @@ var DevToolsService = class {
|
|
|
2245
3495
|
}
|
|
2246
3496
|
exposeToWindow() {
|
|
2247
3497
|
if (typeof window !== "undefined") {
|
|
2248
|
-
window.
|
|
3498
|
+
window.__00__ = {
|
|
2249
3499
|
version: this.version,
|
|
2250
3500
|
getState: () => this.getState(),
|
|
2251
3501
|
clearHistory: () => {
|
|
2252
3502
|
this.eventsHistory = [];
|
|
2253
3503
|
this.notifyDevTools();
|
|
2254
3504
|
},
|
|
3505
|
+
refreshVersions: () => this.refreshBackendVersions(),
|
|
2255
3506
|
getTableData: async (tableName) => {
|
|
2256
3507
|
try {
|
|
2257
3508
|
const result = await this.databaseService.query(`SELECT * FROM ${tableName}`);
|
|
@@ -2266,7 +3517,7 @@ var DevToolsService = class {
|
|
|
2266
3517
|
} catch (e) {
|
|
2267
3518
|
this.logger.error({
|
|
2268
3519
|
err: e,
|
|
2269
|
-
Category: "
|
|
3520
|
+
Category: "sp00ky-client::DevToolsService::exposeToWindow"
|
|
2270
3521
|
}, "Failed to get table data");
|
|
2271
3522
|
return [];
|
|
2272
3523
|
}
|
|
@@ -2298,7 +3549,7 @@ var DevToolsService = class {
|
|
|
2298
3549
|
this.logger.debug({
|
|
2299
3550
|
query,
|
|
2300
3551
|
target,
|
|
2301
|
-
Category: "
|
|
3552
|
+
Category: "sp00ky-client::DevToolsService::runQuery"
|
|
2302
3553
|
}, "Running query (START)");
|
|
2303
3554
|
const service = target === "remote" ? this.remoteDatabaseService : this.databaseService;
|
|
2304
3555
|
const startTime = Date.now();
|
|
@@ -2309,7 +3560,7 @@ var DevToolsService = class {
|
|
|
2309
3560
|
time: queryTime,
|
|
2310
3561
|
resultType: typeof result,
|
|
2311
3562
|
isArray: Array.isArray(result),
|
|
2312
|
-
Category: "
|
|
3563
|
+
Category: "sp00ky-client::DevToolsService::runQuery"
|
|
2313
3564
|
}, "Database returned result");
|
|
2314
3565
|
const serializeStart = Date.now();
|
|
2315
3566
|
const serialized = this.serializeForDevTools(result);
|
|
@@ -2317,7 +3568,7 @@ var DevToolsService = class {
|
|
|
2317
3568
|
this.logger.debug({
|
|
2318
3569
|
serializeTime,
|
|
2319
3570
|
serializedLength: JSON.stringify(serialized).length,
|
|
2320
|
-
Category: "
|
|
3571
|
+
Category: "sp00ky-client::DevToolsService::runQuery"
|
|
2321
3572
|
}, "Serialization complete");
|
|
2322
3573
|
return {
|
|
2323
3574
|
success: true,
|
|
@@ -2329,7 +3580,7 @@ var DevToolsService = class {
|
|
|
2329
3580
|
err: e,
|
|
2330
3581
|
query,
|
|
2331
3582
|
target,
|
|
2332
|
-
Category: "
|
|
3583
|
+
Category: "sp00ky-client::DevToolsService::runQuery"
|
|
2333
3584
|
}, "Query execution failed");
|
|
2334
3585
|
return {
|
|
2335
3586
|
success: false,
|
|
@@ -2339,23 +3590,52 @@ var DevToolsService = class {
|
|
|
2339
3590
|
}
|
|
2340
3591
|
};
|
|
2341
3592
|
window.postMessage({
|
|
2342
|
-
type: "
|
|
2343
|
-
source: "
|
|
3593
|
+
type: "SP00KY_DETECTED",
|
|
3594
|
+
source: "sp00ky-devtools-page",
|
|
2344
3595
|
data: {
|
|
2345
3596
|
version: this.version,
|
|
2346
3597
|
detected: true
|
|
2347
3598
|
}
|
|
2348
3599
|
}, "*");
|
|
3600
|
+
window.dispatchEvent(new CustomEvent("sp00ky:init"));
|
|
2349
3601
|
}
|
|
2350
3602
|
}
|
|
2351
3603
|
};
|
|
2352
3604
|
|
|
2353
3605
|
//#endregion
|
|
2354
3606
|
//#region src/modules/auth/index.ts
|
|
3607
|
+
/**
|
|
3608
|
+
* Read the `AC` (access-method name) claim from a SurrealDB record-access
|
|
3609
|
+
* JWT without verifying it — we only need the claim, the server enforces the
|
|
3610
|
+
* token. Returns null on any malformed input. The in-browser SSP needs this
|
|
3611
|
+
* to resolve `$access` in table permission predicates (mirrors the session's
|
|
3612
|
+
* `$access` that the server's `fn::query::register` reads).
|
|
3613
|
+
*/
|
|
3614
|
+
function decodeAccessFromToken(token) {
|
|
3615
|
+
try {
|
|
3616
|
+
const payload = token.split(".")[1];
|
|
3617
|
+
if (!payload) return null;
|
|
3618
|
+
let b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
|
|
3619
|
+
b64 += "=".repeat((4 - b64.length % 4) % 4);
|
|
3620
|
+
const json = typeof atob === "function" ? atob(b64) : Buffer.from(b64, "base64").toString("binary");
|
|
3621
|
+
const claims = JSON.parse(json);
|
|
3622
|
+
const ac = claims.AC ?? claims.ac;
|
|
3623
|
+
return typeof ac === "string" ? ac : null;
|
|
3624
|
+
} catch {
|
|
3625
|
+
return null;
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
2355
3628
|
var AuthService = class {
|
|
2356
3629
|
token = null;
|
|
2357
3630
|
currentUser = null;
|
|
2358
3631
|
isAuthenticated = false;
|
|
3632
|
+
/**
|
|
3633
|
+
* The record-access method name for the current session (e.g. `"account"`),
|
|
3634
|
+
* derived from the token's `AC` claim. Consumed by the in-browser SSP's
|
|
3635
|
+
* permission injection so `$access`-gated table predicates resolve locally,
|
|
3636
|
+
* mirroring the server's `$access`. Null when logged out.
|
|
3637
|
+
*/
|
|
3638
|
+
access = null;
|
|
2359
3639
|
isLoading = true;
|
|
2360
3640
|
events = createAuthEventSystem();
|
|
2361
3641
|
get eventSystem() {
|
|
@@ -2396,9 +3676,9 @@ var AuthService = class {
|
|
|
2396
3676
|
async check(accessToken) {
|
|
2397
3677
|
this.isLoading = true;
|
|
2398
3678
|
try {
|
|
2399
|
-
const token = accessToken || await this.persistenceClient.get("
|
|
3679
|
+
const token = accessToken || await this.persistenceClient.get("sp00ky_auth_token");
|
|
2400
3680
|
if (!token) {
|
|
2401
|
-
this.logger.debug({ Category: "
|
|
3681
|
+
this.logger.debug({ Category: "sp00ky-client::AuthService::check" }, "No token found in storage or arguments");
|
|
2402
3682
|
this.isLoading = false;
|
|
2403
3683
|
this.isAuthenticated = false;
|
|
2404
3684
|
this.notifyListeners();
|
|
@@ -2411,22 +3691,22 @@ var AuthService = class {
|
|
|
2411
3691
|
if (user && user.id) {
|
|
2412
3692
|
this.logger.info({
|
|
2413
3693
|
user,
|
|
2414
|
-
Category: "
|
|
3694
|
+
Category: "sp00ky-client::AuthService::check"
|
|
2415
3695
|
}, "Auth check complete (via $auth.id)");
|
|
2416
3696
|
await this.setSession(token, user);
|
|
2417
3697
|
} else {
|
|
2418
|
-
this.logger.warn({ Category: "
|
|
3698
|
+
this.logger.warn({ Category: "sp00ky-client::AuthService::check" }, "$auth.id empty, attempting manual user fetch");
|
|
2419
3699
|
const manualResult = await this.remote.query("SELECT * FROM user WHERE id = $auth.id LIMIT 1");
|
|
2420
3700
|
const manualItems = Array.isArray(manualResult) && Array.isArray(manualResult[0]) ? manualResult[0] : manualResult;
|
|
2421
3701
|
const manualUser = Array.isArray(manualItems) ? manualItems[0] : manualItems;
|
|
2422
3702
|
if (manualUser && manualUser.id) {
|
|
2423
3703
|
this.logger.info({
|
|
2424
3704
|
user: manualUser,
|
|
2425
|
-
Category: "
|
|
3705
|
+
Category: "sp00ky-client::AuthService::check"
|
|
2426
3706
|
}, "Auth check complete (via manual fetch)");
|
|
2427
3707
|
await this.setSession(token, manualUser);
|
|
2428
3708
|
} else {
|
|
2429
|
-
this.logger.warn({ Category: "
|
|
3709
|
+
this.logger.warn({ Category: "sp00ky-client::AuthService::check" }, "Token valid but user not found via fallback");
|
|
2430
3710
|
await this.signOut();
|
|
2431
3711
|
}
|
|
2432
3712
|
}
|
|
@@ -2434,7 +3714,7 @@ var AuthService = class {
|
|
|
2434
3714
|
this.logger.error({
|
|
2435
3715
|
error,
|
|
2436
3716
|
stack: error.stack,
|
|
2437
|
-
Category: "
|
|
3717
|
+
Category: "sp00ky-client::AuthService::check"
|
|
2438
3718
|
}, "Auth check failed");
|
|
2439
3719
|
await this.signOut();
|
|
2440
3720
|
} finally {
|
|
@@ -2448,19 +3728,27 @@ var AuthService = class {
|
|
|
2448
3728
|
this.token = null;
|
|
2449
3729
|
this.currentUser = null;
|
|
2450
3730
|
this.isAuthenticated = false;
|
|
2451
|
-
|
|
3731
|
+
this.access = null;
|
|
3732
|
+
await this.persistenceClient.remove("sp00ky_auth_token");
|
|
2452
3733
|
try {
|
|
2453
3734
|
await this.remote.getClient().invalidate();
|
|
2454
|
-
} catch (
|
|
3735
|
+
} catch (_e) {}
|
|
2455
3736
|
this.notifyListeners();
|
|
2456
3737
|
}
|
|
2457
3738
|
async setSession(token, user) {
|
|
2458
3739
|
this.token = token;
|
|
2459
3740
|
this.currentUser = user;
|
|
2460
3741
|
this.isAuthenticated = true;
|
|
2461
|
-
|
|
3742
|
+
this.access = decodeAccessFromToken(token) ?? this.defaultAccessName();
|
|
3743
|
+
await this.persistenceClient.set("sp00ky_auth_token", token);
|
|
2462
3744
|
this.notifyListeners();
|
|
2463
3745
|
}
|
|
3746
|
+
/** Fallback when the token carries no `AC` claim: if the schema defines
|
|
3747
|
+
* exactly one record-access method, assume the session used it. */
|
|
3748
|
+
defaultAccessName() {
|
|
3749
|
+
const names = Object.keys(this.schema.access ?? {});
|
|
3750
|
+
return names.length === 1 ? names[0] : null;
|
|
3751
|
+
}
|
|
2464
3752
|
async signUp(accessName, params) {
|
|
2465
3753
|
const def = this.getAccessDefinition(accessName);
|
|
2466
3754
|
if (!def) throw new Error(`Access definition '${accessName}' not found`);
|
|
@@ -2470,13 +3758,13 @@ var AuthService = class {
|
|
|
2470
3758
|
this.logger.info({
|
|
2471
3759
|
accessName,
|
|
2472
3760
|
runtimeParams,
|
|
2473
|
-
Category: "
|
|
3761
|
+
Category: "sp00ky-client::AuthService::signUp"
|
|
2474
3762
|
}, "Attempting signup");
|
|
2475
3763
|
const { access } = await this.remote.getClient().signup({
|
|
2476
3764
|
access: accessName,
|
|
2477
3765
|
variables: runtimeParams
|
|
2478
3766
|
});
|
|
2479
|
-
this.logger.info({ Category: "
|
|
3767
|
+
this.logger.info({ Category: "sp00ky-client::AuthService::signUp" }, "Signup successful, token received");
|
|
2480
3768
|
await this.check(access);
|
|
2481
3769
|
}
|
|
2482
3770
|
async signIn(accessName, params) {
|
|
@@ -2487,7 +3775,7 @@ var AuthService = class {
|
|
|
2487
3775
|
if (missingParams.length > 0) throw new Error(`Missing required signin params for '${accessName}': ${missingParams.join(", ")}`);
|
|
2488
3776
|
this.logger.info({
|
|
2489
3777
|
accessName,
|
|
2490
|
-
Category: "
|
|
3778
|
+
Category: "sp00ky-client::AuthService::signIn"
|
|
2491
3779
|
}, "Attempting signin");
|
|
2492
3780
|
const { access } = await this.remote.getClient().signin({
|
|
2493
3781
|
access: accessName,
|
|
@@ -2504,6 +3792,12 @@ var StreamProcessorService = class {
|
|
|
2504
3792
|
processor;
|
|
2505
3793
|
isInitialized = false;
|
|
2506
3794
|
receivers = [];
|
|
3795
|
+
batching = false;
|
|
3796
|
+
batchBuffer = /* @__PURE__ */ new Map();
|
|
3797
|
+
sessionAuth = {
|
|
3798
|
+
authId: "",
|
|
3799
|
+
access: ""
|
|
3800
|
+
};
|
|
2507
3801
|
constructor(events, db, persistenceClient, logger) {
|
|
2508
3802
|
this.events = events;
|
|
2509
3803
|
this.db = db;
|
|
@@ -2518,25 +3812,91 @@ var StreamProcessorService = class {
|
|
|
2518
3812
|
this.receivers.push(receiver);
|
|
2519
3813
|
}
|
|
2520
3814
|
notifyUpdates(updates) {
|
|
3815
|
+
if (this.batching) {
|
|
3816
|
+
for (const update of updates) {
|
|
3817
|
+
const prev = this.batchBuffer.get(update.queryHash);
|
|
3818
|
+
const sum = (a, b) => (a ?? 0) + (b ?? 0);
|
|
3819
|
+
this.batchBuffer.set(update.queryHash, {
|
|
3820
|
+
...update,
|
|
3821
|
+
op: "CREATE",
|
|
3822
|
+
materializationTimeMs: sum(prev?.materializationTimeMs, update.materializationTimeMs),
|
|
3823
|
+
storeApplyMs: sum(prev?.storeApplyMs, update.storeApplyMs),
|
|
3824
|
+
circuitStepMs: sum(prev?.circuitStepMs, update.circuitStepMs),
|
|
3825
|
+
transformMs: sum(prev?.transformMs, update.transformMs)
|
|
3826
|
+
});
|
|
3827
|
+
}
|
|
3828
|
+
return;
|
|
3829
|
+
}
|
|
3830
|
+
this.dispatchUpdates(updates);
|
|
3831
|
+
}
|
|
3832
|
+
dispatchUpdates(updates) {
|
|
2521
3833
|
for (const update of updates) for (const receiver of this.receivers) receiver.onStreamUpdate(update);
|
|
2522
3834
|
}
|
|
2523
3835
|
/**
|
|
3836
|
+
* Ingest a batch of record changes as a single bulk operation, firing only
|
|
3837
|
+
* one coalesced `StreamUpdate` per affected query once every record has been
|
|
3838
|
+
* ingested (instead of one update per record). Use this whenever multiple
|
|
3839
|
+
* records land at once — e.g. sync fetching N missing rows — so a list query
|
|
3840
|
+
* re-runs and the UI re-renders once for the whole batch rather than
|
|
3841
|
+
* row-by-row.
|
|
3842
|
+
*
|
|
3843
|
+
* Internally opens a coalescing window, ingests each record, then flushes;
|
|
3844
|
+
* processor state is persisted once for the whole batch. No-op for an empty
|
|
3845
|
+
* batch.
|
|
3846
|
+
*/
|
|
3847
|
+
ingestMany(records) {
|
|
3848
|
+
if (records.length === 0) return;
|
|
3849
|
+
this.beginCoalescing();
|
|
3850
|
+
try {
|
|
3851
|
+
for (const record of records) this.ingest(record.table, record.op, record.id, record.record);
|
|
3852
|
+
} finally {
|
|
3853
|
+
this.flushCoalescing();
|
|
3854
|
+
}
|
|
3855
|
+
}
|
|
3856
|
+
/**
|
|
3857
|
+
* Open a coalescing window. While open, the per-record stream updates
|
|
3858
|
+
* emitted by `ingest` are buffered (one entry per queryHash) instead of
|
|
3859
|
+
* dispatched. Always paired with `flushCoalescing()` in a try/finally by
|
|
3860
|
+
* `ingestMany` so the window always closes — otherwise the processor stays
|
|
3861
|
+
* stuck buffering forever.
|
|
3862
|
+
*
|
|
3863
|
+
* No-op if a window is already open (nested batches aren't expected here).
|
|
3864
|
+
*/
|
|
3865
|
+
beginCoalescing() {
|
|
3866
|
+
if (this.batching) return;
|
|
3867
|
+
this.batching = true;
|
|
3868
|
+
this.batchBuffer.clear();
|
|
3869
|
+
}
|
|
3870
|
+
/**
|
|
3871
|
+
* Close the coalescing window and flush: dispatch one coalesced
|
|
3872
|
+
* `StreamUpdate` per buffered queryHash, then persist processor state once
|
|
3873
|
+
* for the whole batch (instead of once per ingest).
|
|
3874
|
+
*/
|
|
3875
|
+
flushCoalescing() {
|
|
3876
|
+
if (!this.batching) return;
|
|
3877
|
+
this.batching = false;
|
|
3878
|
+
const buffered = Array.from(this.batchBuffer.values());
|
|
3879
|
+
this.batchBuffer.clear();
|
|
3880
|
+
if (buffered.length > 0) this.dispatchUpdates(buffered);
|
|
3881
|
+
this.saveState();
|
|
3882
|
+
}
|
|
3883
|
+
/**
|
|
2524
3884
|
* Initialize the WASM module and processor.
|
|
2525
3885
|
* This must be called before using other methods.
|
|
2526
3886
|
*/
|
|
2527
3887
|
async init() {
|
|
2528
3888
|
if (this.isInitialized) return;
|
|
2529
|
-
this.logger.info({ Category: "
|
|
3889
|
+
this.logger.info({ Category: "sp00ky-client::StreamProcessorService::init" }, "Initializing WASM...");
|
|
2530
3890
|
try {
|
|
2531
3891
|
await init();
|
|
2532
|
-
this.processor = new
|
|
3892
|
+
this.processor = new Sp00kyProcessor();
|
|
2533
3893
|
await this.loadState();
|
|
2534
3894
|
this.isInitialized = true;
|
|
2535
|
-
this.logger.info({ Category: "
|
|
3895
|
+
this.logger.info({ Category: "sp00ky-client::StreamProcessorService::init" }, "Initialized successfully");
|
|
2536
3896
|
} catch (e) {
|
|
2537
3897
|
this.logger.error({
|
|
2538
3898
|
error: e,
|
|
2539
|
-
Category: "
|
|
3899
|
+
Category: "sp00ky-client::StreamProcessorService::init"
|
|
2540
3900
|
}, "Failed to initialize");
|
|
2541
3901
|
throw e;
|
|
2542
3902
|
}
|
|
@@ -2544,37 +3904,75 @@ var StreamProcessorService = class {
|
|
|
2544
3904
|
async loadState() {
|
|
2545
3905
|
if (!this.processor) return;
|
|
2546
3906
|
try {
|
|
2547
|
-
const result = await this.persistenceClient.get("
|
|
3907
|
+
const result = await this.persistenceClient.get("_00_stream_processor_state");
|
|
2548
3908
|
if (Array.isArray(result) && result.length > 0 && Array.isArray(result[0]) && result[0].length > 0 && result[0][0]?.state) {
|
|
2549
3909
|
const state = result[0][0].state;
|
|
2550
3910
|
this.logger.info({
|
|
2551
3911
|
stateLength: state.length,
|
|
2552
|
-
Category: "
|
|
3912
|
+
Category: "sp00ky-client::StreamProcessorService::loadState"
|
|
2553
3913
|
}, "Loading state from DB");
|
|
2554
3914
|
if (typeof this.processor.load_state === "function") this.processor.load_state(state);
|
|
2555
|
-
else this.logger.warn({ Category: "
|
|
2556
|
-
} else this.logger.info({ Category: "
|
|
3915
|
+
else this.logger.warn({ Category: "sp00ky-client::StreamProcessorService::loadState" }, "load_state method not found on processor");
|
|
3916
|
+
} else this.logger.info({ Category: "sp00ky-client::StreamProcessorService::loadState" }, "No saved state found");
|
|
2557
3917
|
} catch (e) {
|
|
2558
3918
|
this.logger.error({
|
|
2559
3919
|
error: e,
|
|
2560
|
-
Category: "
|
|
3920
|
+
Category: "sp00ky-client::StreamProcessorService::loadState"
|
|
2561
3921
|
}, "Failed to load state");
|
|
2562
3922
|
}
|
|
2563
3923
|
}
|
|
3924
|
+
/**
|
|
3925
|
+
* Seed per-table `select` permission predicates ({ [table]: whereText }).
|
|
3926
|
+
* Must run after the processor exists and before any `register_view`, else
|
|
3927
|
+
* non-`_00_` tables are default-denied and registration fails.
|
|
3928
|
+
*/
|
|
3929
|
+
setPermissions(permissions) {
|
|
3930
|
+
if (!this.processor) return;
|
|
3931
|
+
if (typeof this.processor.set_permissions !== "function") {
|
|
3932
|
+
this.logger.warn({ Category: "sp00ky-client::StreamProcessorService::setPermissions" }, "set_permissions not found on processor (stale WASM build?)");
|
|
3933
|
+
return;
|
|
3934
|
+
}
|
|
3935
|
+
this.processor.set_permissions(permissions);
|
|
3936
|
+
this.logger.info({
|
|
3937
|
+
tables: Object.keys(permissions).length,
|
|
3938
|
+
Category: "sp00ky-client::StreamProcessorService::setPermissions"
|
|
3939
|
+
}, "Seeded table permissions");
|
|
3940
|
+
}
|
|
3941
|
+
/**
|
|
3942
|
+
* Set the current session's auth identity for permission injection,
|
|
3943
|
+
* mirroring the server's `fn::query::register`
|
|
3944
|
+
* (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
|
|
3945
|
+
* Stored as strings (empty when logged out) and applied to every
|
|
3946
|
+
* `register_view` in {@link registerQueryPlan}. Must be set before a
|
|
3947
|
+
* `$auth`-gated query registers (and re-set on auth state changes), or the
|
|
3948
|
+
* in-browser SSP's `permission_inject` rejects it with
|
|
3949
|
+
* "requires $auth but registration params lack it".
|
|
3950
|
+
*/
|
|
3951
|
+
setSessionAuth(authId, access) {
|
|
3952
|
+
this.sessionAuth = {
|
|
3953
|
+
authId: authId ?? "",
|
|
3954
|
+
access: access ?? ""
|
|
3955
|
+
};
|
|
3956
|
+
this.logger.debug({
|
|
3957
|
+
authId: this.sessionAuth.authId,
|
|
3958
|
+
access: this.sessionAuth.access,
|
|
3959
|
+
Category: "sp00ky-client::StreamProcessorService::setSessionAuth"
|
|
3960
|
+
}, "Session auth context updated");
|
|
3961
|
+
}
|
|
2564
3962
|
async saveState() {
|
|
2565
3963
|
if (!this.processor) return;
|
|
2566
3964
|
try {
|
|
2567
3965
|
if (typeof this.processor.save_state === "function") {
|
|
2568
3966
|
const state = this.processor.save_state();
|
|
2569
3967
|
if (state) {
|
|
2570
|
-
await this.persistenceClient.set("
|
|
2571
|
-
this.logger.trace({ Category: "
|
|
3968
|
+
await this.persistenceClient.set("_00_stream_processor_state", state);
|
|
3969
|
+
this.logger.trace({ Category: "sp00ky-client::StreamProcessorService::saveState" }, "State saved");
|
|
2572
3970
|
}
|
|
2573
3971
|
}
|
|
2574
3972
|
} catch (e) {
|
|
2575
3973
|
this.logger.error({
|
|
2576
3974
|
error: e,
|
|
2577
|
-
Category: "
|
|
3975
|
+
Category: "sp00ky-client::StreamProcessorService::saveState"
|
|
2578
3976
|
}, "Failed to save state");
|
|
2579
3977
|
}
|
|
2580
3978
|
}
|
|
@@ -2588,36 +3986,43 @@ var StreamProcessorService = class {
|
|
|
2588
3986
|
table,
|
|
2589
3987
|
op,
|
|
2590
3988
|
id,
|
|
2591
|
-
Category: "
|
|
3989
|
+
Category: "sp00ky-client::StreamProcessorService::ingest"
|
|
2592
3990
|
}, "Ingesting into ssp");
|
|
2593
3991
|
if (!this.processor) {
|
|
2594
|
-
this.logger.warn({ Category: "
|
|
3992
|
+
this.logger.warn({ Category: "sp00ky-client::StreamProcessorService::ingest" }, "Not initialized, skipping ingest");
|
|
2595
3993
|
return [];
|
|
2596
3994
|
}
|
|
2597
3995
|
try {
|
|
2598
3996
|
const normalizedRecord = this.normalizeValue(record);
|
|
3997
|
+
const t0 = performance.now();
|
|
2599
3998
|
const rawUpdates = this.processor.ingest(table, op, id, normalizedRecord);
|
|
3999
|
+
const materializationTimeMs = performance.now() - t0;
|
|
2600
4000
|
this.logger.debug({
|
|
2601
4001
|
table,
|
|
2602
4002
|
op,
|
|
2603
4003
|
id,
|
|
2604
4004
|
rawUpdates: rawUpdates.length,
|
|
2605
|
-
|
|
4005
|
+
materializationTimeMs,
|
|
4006
|
+
Category: "sp00ky-client::StreamProcessorService::ingest"
|
|
2606
4007
|
}, "Ingesting into ssp done");
|
|
2607
4008
|
if (rawUpdates && Array.isArray(rawUpdates) && rawUpdates.length > 0) {
|
|
2608
4009
|
const updates = rawUpdates.map((u) => ({
|
|
2609
4010
|
queryHash: u.query_id,
|
|
2610
4011
|
localArray: u.result_data,
|
|
2611
|
-
op
|
|
4012
|
+
op,
|
|
4013
|
+
materializationTimeMs,
|
|
4014
|
+
storeApplyMs: u.timing_store_apply_ms,
|
|
4015
|
+
circuitStepMs: u.timing_circuit_step_ms,
|
|
4016
|
+
transformMs: u.timing_transform_ms
|
|
2612
4017
|
}));
|
|
2613
4018
|
this.notifyUpdates(updates);
|
|
2614
4019
|
}
|
|
2615
|
-
this.saveState();
|
|
4020
|
+
if (!this.batching) this.saveState();
|
|
2616
4021
|
return rawUpdates;
|
|
2617
4022
|
} catch (e) {
|
|
2618
4023
|
this.logger.error({
|
|
2619
4024
|
error: e,
|
|
2620
|
-
Category: "
|
|
4025
|
+
Category: "sp00ky-client::StreamProcessorService::ingest"
|
|
2621
4026
|
}, "Ingesting into ssp failed");
|
|
2622
4027
|
}
|
|
2623
4028
|
return [];
|
|
@@ -2628,46 +4033,55 @@ var StreamProcessorService = class {
|
|
|
2628
4033
|
*/
|
|
2629
4034
|
registerQueryPlan(queryPlan) {
|
|
2630
4035
|
if (!this.processor) {
|
|
2631
|
-
this.logger.warn({ Category: "
|
|
4036
|
+
this.logger.warn({ Category: "sp00ky-client::StreamProcessorService::registerQueryPlan" }, "Not initialized, skipping registration");
|
|
2632
4037
|
return;
|
|
2633
4038
|
}
|
|
2634
4039
|
this.logger.debug({
|
|
2635
4040
|
queryHash: queryPlan.queryHash,
|
|
2636
4041
|
surql: queryPlan.surql,
|
|
2637
4042
|
params: queryPlan.params,
|
|
2638
|
-
Category: "
|
|
4043
|
+
Category: "sp00ky-client::StreamProcessorService::registerQueryPlan"
|
|
2639
4044
|
}, "Registering query plan");
|
|
2640
4045
|
try {
|
|
2641
|
-
const
|
|
4046
|
+
const paramsWithAuth = {
|
|
4047
|
+
...this.normalizeValue(queryPlan.params),
|
|
4048
|
+
auth: { id: this.sessionAuth.authId },
|
|
4049
|
+
access: this.sessionAuth.access
|
|
4050
|
+
};
|
|
2642
4051
|
const initialUpdate = this.processor.register_view({
|
|
2643
4052
|
id: queryPlan.queryHash,
|
|
2644
4053
|
surql: queryPlan.surql,
|
|
2645
|
-
params:
|
|
4054
|
+
params: paramsWithAuth,
|
|
2646
4055
|
clientId: "local",
|
|
2647
4056
|
ttl: queryPlan.ttl.toString(),
|
|
2648
4057
|
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2649
4058
|
});
|
|
2650
4059
|
this.logger.debug({
|
|
2651
4060
|
initialUpdate,
|
|
2652
|
-
Category: "
|
|
4061
|
+
Category: "sp00ky-client::StreamProcessorService::registerQueryPlan"
|
|
2653
4062
|
}, "register_view result");
|
|
2654
4063
|
if (!initialUpdate) throw new Error("Failed to register query plan");
|
|
2655
4064
|
const update = {
|
|
2656
4065
|
queryHash: initialUpdate.query_id,
|
|
2657
|
-
localArray: initialUpdate.result_data
|
|
4066
|
+
localArray: initialUpdate.result_data,
|
|
4067
|
+
registration: {
|
|
4068
|
+
parseMs: initialUpdate.timing_parse_ms ?? 0,
|
|
4069
|
+
planMs: initialUpdate.timing_plan_ms ?? 0,
|
|
4070
|
+
snapshotMs: initialUpdate.timing_snapshot_ms ?? 0
|
|
4071
|
+
}
|
|
2658
4072
|
};
|
|
2659
4073
|
this.saveState();
|
|
2660
4074
|
this.logger.debug({
|
|
2661
4075
|
queryHash: queryPlan.queryHash,
|
|
2662
4076
|
surql: queryPlan.surql,
|
|
2663
4077
|
params: queryPlan.params,
|
|
2664
|
-
Category: "
|
|
4078
|
+
Category: "sp00ky-client::StreamProcessorService::registerQueryPlan"
|
|
2665
4079
|
}, "Registered query plan");
|
|
2666
4080
|
return update;
|
|
2667
4081
|
} catch (e) {
|
|
2668
4082
|
this.logger.error({
|
|
2669
4083
|
error: e,
|
|
2670
|
-
Category: "
|
|
4084
|
+
Category: "sp00ky-client::StreamProcessorService::registerQueryPlan"
|
|
2671
4085
|
}, "Error registering query plan");
|
|
2672
4086
|
throw e;
|
|
2673
4087
|
}
|
|
@@ -2683,13 +4097,14 @@ var StreamProcessorService = class {
|
|
|
2683
4097
|
} catch (e) {
|
|
2684
4098
|
this.logger.error({
|
|
2685
4099
|
error: e,
|
|
2686
|
-
Category: "
|
|
4100
|
+
Category: "sp00ky-client::StreamProcessorService::unregisterQueryPlan"
|
|
2687
4101
|
}, "Error unregistering query plan");
|
|
2688
4102
|
}
|
|
2689
4103
|
}
|
|
2690
4104
|
normalizeValue(value) {
|
|
2691
4105
|
if (value === null || value === void 0) return value;
|
|
2692
4106
|
if (typeof value === "object") {
|
|
4107
|
+
if (value instanceof Uint8Array || value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return null;
|
|
2693
4108
|
const hasTable = "table" in value && typeof value.table?.toString === "function";
|
|
2694
4109
|
const hasId = "id" in value;
|
|
2695
4110
|
const hasToString = typeof value.toString === "function";
|
|
@@ -2698,7 +4113,7 @@ var StreamProcessorService = class {
|
|
|
2698
4113
|
const result = value.toString();
|
|
2699
4114
|
this.logger.trace({
|
|
2700
4115
|
result,
|
|
2701
|
-
Category: "
|
|
4116
|
+
Category: "sp00ky-client::StreamProcessorService::normalizeValue"
|
|
2702
4117
|
}, "RecordId detected");
|
|
2703
4118
|
return result;
|
|
2704
4119
|
}
|
|
@@ -2714,6 +4129,51 @@ var StreamProcessorService = class {
|
|
|
2714
4129
|
}
|
|
2715
4130
|
};
|
|
2716
4131
|
|
|
4132
|
+
//#endregion
|
|
4133
|
+
//#region src/services/stream-processor/permissions.ts
|
|
4134
|
+
/**
|
|
4135
|
+
* Extract per-table `select` permission predicates from a raw `.surql` schema.
|
|
4136
|
+
*
|
|
4137
|
+
* The in-browser SSP default-denies any non-`_00_` table that has no permission
|
|
4138
|
+
* predicate registered (see `permission_inject::build_predicate`). The client
|
|
4139
|
+
* already holds the full schema text (`config.schemaSurql`), so we parse each
|
|
4140
|
+
* `DEFINE TABLE … PERMISSIONS …` clause and hand the `select` predicate to the
|
|
4141
|
+
* processor via `set_permissions` at boot — mirroring the native path that
|
|
4142
|
+
* seeds the same map from `INFO FOR DB`.
|
|
4143
|
+
*
|
|
4144
|
+
* Returns `{ [table]: whereText }` where `whereText` is the raw SurrealQL
|
|
4145
|
+
* expression (`'true'` for `FULL`, `'false'` for `NONE` or a table with no
|
|
4146
|
+
* `select` permission).
|
|
4147
|
+
*/
|
|
4148
|
+
function extractSelectPermissions(schemaSurql) {
|
|
4149
|
+
const out = {};
|
|
4150
|
+
if (!schemaSurql) return out;
|
|
4151
|
+
const cleaned = schemaSurql.replace(/--[^\n]*/g, "");
|
|
4152
|
+
const tableStmt = /DEFINE\s+TABLE\s+(?:OVERWRITE\s+|IF\s+NOT\s+EXISTS\s+)?([A-Za-z_][\w]*)\b([^;]*);/gi;
|
|
4153
|
+
let m;
|
|
4154
|
+
while ((m = tableStmt.exec(cleaned)) !== null) {
|
|
4155
|
+
const table = m[1];
|
|
4156
|
+
const body = m[2];
|
|
4157
|
+
out[table] = selectPredicateFromBody(body);
|
|
4158
|
+
}
|
|
4159
|
+
return out;
|
|
4160
|
+
}
|
|
4161
|
+
function selectPredicateFromBody(body) {
|
|
4162
|
+
const permIdx = body.search(/\bPERMISSIONS\b/i);
|
|
4163
|
+
if (permIdx === -1) return "false";
|
|
4164
|
+
const perms = body.slice(permIdx + 11).trim();
|
|
4165
|
+
if (/^FULL\b/i.test(perms)) return "true";
|
|
4166
|
+
if (/^NONE\b/i.test(perms)) return "false";
|
|
4167
|
+
const groups = perms.split(/\bFOR\b/i).map((g) => g.trim()).filter(Boolean);
|
|
4168
|
+
for (const group of groups) {
|
|
4169
|
+
const where = group.search(/\bWHERE\b/i);
|
|
4170
|
+
if (where === -1) continue;
|
|
4171
|
+
const actions = group.slice(0, where).toLowerCase();
|
|
4172
|
+
if (/\bselect\b/.test(actions)) return group.slice(where + 5).trim();
|
|
4173
|
+
}
|
|
4174
|
+
return "false";
|
|
4175
|
+
}
|
|
4176
|
+
|
|
2717
4177
|
//#endregion
|
|
2718
4178
|
//#region src/modules/cache/index.ts
|
|
2719
4179
|
/**
|
|
@@ -2741,7 +4201,7 @@ var CacheModule = class {
|
|
|
2741
4201
|
this.logger.debug({
|
|
2742
4202
|
queryHash: update.queryHash,
|
|
2743
4203
|
arrayLength: update.localArray?.length,
|
|
2744
|
-
Category: "
|
|
4204
|
+
Category: "sp00ky-client::CacheModule::onStreamUpdate"
|
|
2745
4205
|
}, "Stream update received");
|
|
2746
4206
|
this.streamUpdateCallback(update);
|
|
2747
4207
|
}
|
|
@@ -2764,7 +4224,7 @@ var CacheModule = class {
|
|
|
2764
4224
|
if (records.length === 0) return;
|
|
2765
4225
|
this.logger.debug({
|
|
2766
4226
|
count: records.length,
|
|
2767
|
-
Category: "
|
|
4227
|
+
Category: "sp00ky-client::CacheModule::saveBatch"
|
|
2768
4228
|
}, "Saving record batch");
|
|
2769
4229
|
try {
|
|
2770
4230
|
const populatedRecords = records.map((record) => {
|
|
@@ -2773,13 +4233,13 @@ var CacheModule = class {
|
|
|
2773
4233
|
...record,
|
|
2774
4234
|
record: {
|
|
2775
4235
|
...record.record,
|
|
2776
|
-
|
|
4236
|
+
_00_rv: record.version
|
|
2777
4237
|
}
|
|
2778
4238
|
};
|
|
2779
4239
|
});
|
|
2780
4240
|
if (!skipDbInsert) {
|
|
2781
4241
|
const query = surql.seal(surql.tx(populatedRecords.map((_, i) => {
|
|
2782
|
-
return surql.
|
|
4242
|
+
return surql.upsertMerge(`id${i}`, `content${i}`);
|
|
2783
4243
|
})));
|
|
2784
4244
|
const params = populatedRecords.reduce((acc, record, i) => {
|
|
2785
4245
|
const { id, ...content } = record.record;
|
|
@@ -2791,20 +4251,26 @@ var CacheModule = class {
|
|
|
2791
4251
|
}, {});
|
|
2792
4252
|
await this.local.execute(query, params);
|
|
2793
4253
|
}
|
|
2794
|
-
|
|
4254
|
+
const bulk = populatedRecords.map((record) => {
|
|
2795
4255
|
const recordId = encodeRecordId(record.record.id);
|
|
2796
4256
|
this.versionLookups[recordId] = record.version;
|
|
2797
|
-
|
|
2798
|
-
|
|
4257
|
+
return {
|
|
4258
|
+
table: record.table,
|
|
4259
|
+
op: record.op,
|
|
4260
|
+
id: recordId,
|
|
4261
|
+
record: record.record
|
|
4262
|
+
};
|
|
4263
|
+
});
|
|
4264
|
+
this.streamProcessor.ingestMany(bulk);
|
|
2799
4265
|
this.logger.debug({
|
|
2800
4266
|
count: records.length,
|
|
2801
|
-
Category: "
|
|
4267
|
+
Category: "sp00ky-client::CacheModule::saveBatch"
|
|
2802
4268
|
}, "Batch saved successfully");
|
|
2803
4269
|
} catch (err) {
|
|
2804
4270
|
this.logger.error({
|
|
2805
4271
|
err,
|
|
2806
4272
|
count: records.length,
|
|
2807
|
-
Category: "
|
|
4273
|
+
Category: "sp00ky-client::CacheModule::saveBatch"
|
|
2808
4274
|
}, "Failed to save batch");
|
|
2809
4275
|
throw err;
|
|
2810
4276
|
}
|
|
@@ -2812,27 +4278,27 @@ var CacheModule = class {
|
|
|
2812
4278
|
/**
|
|
2813
4279
|
* Delete a record from local DB and ingest deletion into DBSP
|
|
2814
4280
|
*/
|
|
2815
|
-
async delete(table, id, skipDbDelete = false) {
|
|
4281
|
+
async delete(table, id, skipDbDelete = false, recordData = {}) {
|
|
2816
4282
|
this.logger.debug({
|
|
2817
4283
|
table,
|
|
2818
4284
|
id,
|
|
2819
|
-
Category: "
|
|
4285
|
+
Category: "sp00ky-client::CacheModule::delete"
|
|
2820
4286
|
}, "Deleting record");
|
|
2821
4287
|
try {
|
|
2822
4288
|
if (!skipDbDelete) await this.local.query("DELETE $id", { id: parseRecordIdString(id) });
|
|
2823
4289
|
delete this.versionLookups[id];
|
|
2824
|
-
|
|
4290
|
+
this.streamProcessor.ingest(table, "DELETE", id, recordData);
|
|
2825
4291
|
this.logger.debug({
|
|
2826
4292
|
table,
|
|
2827
4293
|
id,
|
|
2828
|
-
Category: "
|
|
4294
|
+
Category: "sp00ky-client::CacheModule::delete"
|
|
2829
4295
|
}, "Record deleted successfully");
|
|
2830
4296
|
} catch (err) {
|
|
2831
4297
|
this.logger.error({
|
|
2832
4298
|
err,
|
|
2833
4299
|
table,
|
|
2834
4300
|
id,
|
|
2835
|
-
Category: "
|
|
4301
|
+
Category: "sp00ky-client::CacheModule::delete"
|
|
2836
4302
|
}, "Failed to delete record");
|
|
2837
4303
|
throw err;
|
|
2838
4304
|
}
|
|
@@ -2845,7 +4311,7 @@ var CacheModule = class {
|
|
|
2845
4311
|
this.logger.debug({
|
|
2846
4312
|
queryHash: config.queryHash,
|
|
2847
4313
|
surql: config.surql,
|
|
2848
|
-
Category: "
|
|
4314
|
+
Category: "sp00ky-client::CacheModule::registerQuery"
|
|
2849
4315
|
}, "Registering query");
|
|
2850
4316
|
try {
|
|
2851
4317
|
const update = this.streamProcessor.registerQueryPlan({
|
|
@@ -2862,14 +4328,17 @@ var CacheModule = class {
|
|
|
2862
4328
|
this.logger.debug({
|
|
2863
4329
|
queryHash: config.queryHash,
|
|
2864
4330
|
arrayLength: update.localArray?.length,
|
|
2865
|
-
Category: "
|
|
4331
|
+
Category: "sp00ky-client::CacheModule::registerQuery"
|
|
2866
4332
|
}, "Query registered successfully");
|
|
2867
|
-
return {
|
|
4333
|
+
return {
|
|
4334
|
+
localArray: update.localArray,
|
|
4335
|
+
registrationTimings: update.registration
|
|
4336
|
+
};
|
|
2868
4337
|
} catch (err) {
|
|
2869
4338
|
this.logger.error({
|
|
2870
4339
|
err,
|
|
2871
4340
|
queryHash: config.queryHash,
|
|
2872
|
-
Category: "
|
|
4341
|
+
Category: "sp00ky-client::CacheModule::registerQuery"
|
|
2873
4342
|
}, "Failed to register query");
|
|
2874
4343
|
throw err;
|
|
2875
4344
|
}
|
|
@@ -2880,24 +4349,618 @@ var CacheModule = class {
|
|
|
2880
4349
|
unregisterQuery(queryHash) {
|
|
2881
4350
|
this.logger.debug({
|
|
2882
4351
|
queryHash,
|
|
2883
|
-
Category: "
|
|
4352
|
+
Category: "sp00ky-client::CacheModule::unregisterQuery"
|
|
2884
4353
|
}, "Unregistering query");
|
|
2885
4354
|
try {
|
|
2886
4355
|
this.streamProcessor.unregisterQueryPlan(queryHash);
|
|
2887
4356
|
this.logger.debug({
|
|
2888
4357
|
queryHash,
|
|
2889
|
-
Category: "
|
|
4358
|
+
Category: "sp00ky-client::CacheModule::unregisterQuery"
|
|
2890
4359
|
}, "Query unregistered successfully");
|
|
2891
4360
|
} catch (err) {
|
|
2892
4361
|
this.logger.error({
|
|
2893
4362
|
err,
|
|
2894
4363
|
queryHash,
|
|
2895
|
-
Category: "
|
|
4364
|
+
Category: "sp00ky-client::CacheModule::unregisterQuery"
|
|
2896
4365
|
}, "Failed to unregister query");
|
|
2897
4366
|
}
|
|
2898
4367
|
}
|
|
2899
4368
|
};
|
|
2900
4369
|
|
|
4370
|
+
//#endregion
|
|
4371
|
+
//#region src/modules/crdt/crdt-field.ts
|
|
4372
|
+
const CURSOR_COLORS = [
|
|
4373
|
+
"#3b82f6",
|
|
4374
|
+
"#ef4444",
|
|
4375
|
+
"#22c55e",
|
|
4376
|
+
"#f59e0b",
|
|
4377
|
+
"#8b5cf6",
|
|
4378
|
+
"#ec4899",
|
|
4379
|
+
"#14b8a6",
|
|
4380
|
+
"#f97316"
|
|
4381
|
+
];
|
|
4382
|
+
function cursorColorFromName(name) {
|
|
4383
|
+
let hash = 0;
|
|
4384
|
+
for (let i = 0; i < name.length; i++) hash = (hash << 5) - hash + name.charCodeAt(i) | 0;
|
|
4385
|
+
return CURSOR_COLORS[Math.abs(hash) % CURSOR_COLORS.length];
|
|
4386
|
+
}
|
|
4387
|
+
var CrdtField = class {
|
|
4388
|
+
doc;
|
|
4389
|
+
pushTimer = null;
|
|
4390
|
+
local = null;
|
|
4391
|
+
remote = null;
|
|
4392
|
+
recordId = null;
|
|
4393
|
+
sessionId = "";
|
|
4394
|
+
unsubscribe = null;
|
|
4395
|
+
lastPushTime = 0;
|
|
4396
|
+
lastCursorPushTime = 0;
|
|
4397
|
+
loadedFromCrdt = false;
|
|
4398
|
+
pushRetryCount = 0;
|
|
4399
|
+
logger;
|
|
4400
|
+
cursorsEnabled;
|
|
4401
|
+
/** Remote-push debounce. Local writes happen immediately on every Loro
|
|
4402
|
+
* update; the remote UPSERT is coalesced over this window. Configured
|
|
4403
|
+
* via `Sp00kyConfig.crdtDebounceMs`, default 500. */
|
|
4404
|
+
remoteDebounceMs = 500;
|
|
4405
|
+
_onCursorUpdate = null;
|
|
4406
|
+
pendingCursorUpdate = null;
|
|
4407
|
+
/** Callback set by the editor to receive remote cursor updates.
|
|
4408
|
+
* Any cursor data that arrived before this callback was set will be replayed. */
|
|
4409
|
+
set onCursorUpdate(cb) {
|
|
4410
|
+
this._onCursorUpdate = cb;
|
|
4411
|
+
if (cb && this.pendingCursorUpdate) {
|
|
4412
|
+
try {
|
|
4413
|
+
cb(this.pendingCursorUpdate);
|
|
4414
|
+
} catch (e) {
|
|
4415
|
+
this.logger?.warn({
|
|
4416
|
+
error: e,
|
|
4417
|
+
Category: "sp00ky-client::CrdtField::onCursorUpdate"
|
|
4418
|
+
}, "Failed to replay pending cursor update");
|
|
4419
|
+
}
|
|
4420
|
+
this.pendingCursorUpdate = null;
|
|
4421
|
+
}
|
|
4422
|
+
}
|
|
4423
|
+
get onCursorUpdate() {
|
|
4424
|
+
return this._onCursorUpdate;
|
|
4425
|
+
}
|
|
4426
|
+
constructor(fieldName, cursorsEnabled, initialState, logger) {
|
|
4427
|
+
this.fieldName = fieldName;
|
|
4428
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(fieldName)) throw new Error(`CrdtField: refusing unsafe field identifier '${fieldName}' — must match [a-zA-Z_][a-zA-Z0-9_]*`);
|
|
4429
|
+
this.logger = logger ?? null;
|
|
4430
|
+
this.cursorsEnabled = cursorsEnabled;
|
|
4431
|
+
this.doc = new LoroDoc();
|
|
4432
|
+
if (initialState && initialState.length > 0) try {
|
|
4433
|
+
this.doc.import(initialState);
|
|
4434
|
+
this.loadedFromCrdt = true;
|
|
4435
|
+
} catch (e) {
|
|
4436
|
+
this.logger?.warn({
|
|
4437
|
+
error: e,
|
|
4438
|
+
fieldName,
|
|
4439
|
+
Category: "sp00ky-client::CrdtField::constructor"
|
|
4440
|
+
}, "Initial CRDT state is not a valid LoroDoc snapshot — starting empty and will seed from fallback text");
|
|
4441
|
+
}
|
|
4442
|
+
}
|
|
4443
|
+
getDoc() {
|
|
4444
|
+
return this.doc;
|
|
4445
|
+
}
|
|
4446
|
+
/** Whether the LoroDoc was loaded from saved CRDT state */
|
|
4447
|
+
hasContent() {
|
|
4448
|
+
return this.loadedFromCrdt;
|
|
4449
|
+
}
|
|
4450
|
+
startSync(local, remote, recordId, sessionId, debounceMs) {
|
|
4451
|
+
this.local = local;
|
|
4452
|
+
this.remote = remote;
|
|
4453
|
+
this.recordId = recordId;
|
|
4454
|
+
this.sessionId = sessionId;
|
|
4455
|
+
this.remoteDebounceMs = debounceMs;
|
|
4456
|
+
this.unsubscribe = this.doc.subscribeLocalUpdates(() => {
|
|
4457
|
+
this.persistLocal();
|
|
4458
|
+
this.scheduleRemotePush();
|
|
4459
|
+
});
|
|
4460
|
+
}
|
|
4461
|
+
stopSync() {
|
|
4462
|
+
if (this.unsubscribe) {
|
|
4463
|
+
this.unsubscribe();
|
|
4464
|
+
this.unsubscribe = null;
|
|
4465
|
+
}
|
|
4466
|
+
if (this.pushTimer) {
|
|
4467
|
+
clearTimeout(this.pushTimer);
|
|
4468
|
+
this.pushTimer = null;
|
|
4469
|
+
}
|
|
4470
|
+
if (this.remote && this.recordId) this.pushToRemote();
|
|
4471
|
+
}
|
|
4472
|
+
importRemote(state) {
|
|
4473
|
+
if (Date.now() - this.lastPushTime < this.remoteDebounceMs + 200) return;
|
|
4474
|
+
try {
|
|
4475
|
+
this.doc.import(state);
|
|
4476
|
+
this.persistLocal();
|
|
4477
|
+
} catch (e) {
|
|
4478
|
+
this.logger?.warn({
|
|
4479
|
+
error: e,
|
|
4480
|
+
Category: "sp00ky-client::CrdtField::importRemote"
|
|
4481
|
+
}, "Failed to import remote CRDT state");
|
|
4482
|
+
}
|
|
4483
|
+
}
|
|
4484
|
+
exportSnapshot() {
|
|
4485
|
+
return this.doc.export({ mode: "snapshot" });
|
|
4486
|
+
}
|
|
4487
|
+
/** Push this session's cursor blob into the parent row at
|
|
4488
|
+
* `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
|
|
4489
|
+
* field — the editor still calls this method optimistically, but
|
|
4490
|
+
* without `@cursor` on the schema there's nowhere to store the blob.
|
|
4491
|
+
* The UPDATE itself fires the parent table's LIVE feed, so other
|
|
4492
|
+
* browsers receive the cursor change without a separate `_00_rv` bump. */
|
|
4493
|
+
async pushCursorState(encoded) {
|
|
4494
|
+
if (!this.remote || !this.recordId) return;
|
|
4495
|
+
if (!this.cursorsEnabled) return;
|
|
4496
|
+
this.lastCursorPushTime = Date.now();
|
|
4497
|
+
try {
|
|
4498
|
+
const state = encodeBase64(encoded);
|
|
4499
|
+
await this.remote.query(`UPDATE $id SET ${this.fieldName}.cursors[$sid] = $state RETURN NONE;`, {
|
|
4500
|
+
id: parseRecordIdString(this.recordId),
|
|
4501
|
+
sid: this.sessionId,
|
|
4502
|
+
state
|
|
4503
|
+
});
|
|
4504
|
+
} catch (e) {
|
|
4505
|
+
this.logger?.warn({
|
|
4506
|
+
error: e,
|
|
4507
|
+
Category: "sp00ky-client::CrdtField::pushCursorState"
|
|
4508
|
+
}, "Failed to push cursor state");
|
|
4509
|
+
}
|
|
4510
|
+
}
|
|
4511
|
+
/** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
|
|
4512
|
+
importRemoteCursor(base64State) {
|
|
4513
|
+
if (Date.now() - this.lastCursorPushTime < 300) return;
|
|
4514
|
+
try {
|
|
4515
|
+
const data = decodeBase64(base64State);
|
|
4516
|
+
if (this._onCursorUpdate) this._onCursorUpdate(data);
|
|
4517
|
+
else this.pendingCursorUpdate = data;
|
|
4518
|
+
} catch (e) {
|
|
4519
|
+
this.logger?.warn({
|
|
4520
|
+
error: e,
|
|
4521
|
+
Category: "sp00ky-client::CrdtField::importRemoteCursor"
|
|
4522
|
+
}, "Failed to apply remote cursor data");
|
|
4523
|
+
}
|
|
4524
|
+
}
|
|
4525
|
+
scheduleRemotePush() {
|
|
4526
|
+
if (this.pushTimer) clearTimeout(this.pushTimer);
|
|
4527
|
+
this.pushTimer = setTimeout(() => void this.pushToRemote(), this.remoteDebounceMs);
|
|
4528
|
+
}
|
|
4529
|
+
/** SET path inside a parent row for the current snapshot. `@crdt`-only
|
|
4530
|
+
* fields hold the snapshot directly (`<field>`); `@crdt @cursor`
|
|
4531
|
+
* fields hold a `{ state, cursors }` object so the snapshot lives at
|
|
4532
|
+
* `<field>.state` next to per-session cursor blobs. */
|
|
4533
|
+
statePath() {
|
|
4534
|
+
return this.cursorsEnabled ? `${this.fieldName}.state` : this.fieldName;
|
|
4535
|
+
}
|
|
4536
|
+
/** Mirror the LoroDoc snapshot into the parent row locally. Runs on
|
|
4537
|
+
* every local update and every remote import so reloads (online or
|
|
4538
|
+
* offline) see the freshest content immediately. Failures are
|
|
4539
|
+
* swallowed — a stale local write must never block user input. */
|
|
4540
|
+
async persistLocal() {
|
|
4541
|
+
if (!this.local || !this.recordId) return;
|
|
4542
|
+
try {
|
|
4543
|
+
await this.local.query(`UPDATE $id SET ${this.statePath()} = $state RETURN NONE;`, {
|
|
4544
|
+
id: parseRecordIdString(this.recordId),
|
|
4545
|
+
state: this.exportSnapshot()
|
|
4546
|
+
});
|
|
4547
|
+
} catch (e) {
|
|
4548
|
+
this.logger?.debug({
|
|
4549
|
+
error: e,
|
|
4550
|
+
Category: "sp00ky-client::CrdtField::persistLocal"
|
|
4551
|
+
}, "Local CRDT persist failed (best-effort)");
|
|
4552
|
+
}
|
|
4553
|
+
}
|
|
4554
|
+
async pushToRemote() {
|
|
4555
|
+
if (!this.remote || !this.recordId) return;
|
|
4556
|
+
this.lastPushTime = Date.now();
|
|
4557
|
+
try {
|
|
4558
|
+
await this.remote.query(`UPDATE $id SET ${this.statePath()} = $state RETURN NONE;`, {
|
|
4559
|
+
id: parseRecordIdString(this.recordId),
|
|
4560
|
+
state: this.exportSnapshot()
|
|
4561
|
+
});
|
|
4562
|
+
this.pushRetryCount = 0;
|
|
4563
|
+
} catch (e) {
|
|
4564
|
+
this.logger?.warn({
|
|
4565
|
+
error: e,
|
|
4566
|
+
Category: "sp00ky-client::CrdtField::pushToRemote"
|
|
4567
|
+
}, "Failed to push CRDT state to remote");
|
|
4568
|
+
if (this.pushRetryCount < 2) {
|
|
4569
|
+
this.pushRetryCount++;
|
|
4570
|
+
this.scheduleRemotePush();
|
|
4571
|
+
}
|
|
4572
|
+
}
|
|
4573
|
+
}
|
|
4574
|
+
};
|
|
4575
|
+
function decodeBase64(b64) {
|
|
4576
|
+
if (typeof atob === "function") {
|
|
4577
|
+
const binary = atob(b64);
|
|
4578
|
+
const bytes = new Uint8Array(binary.length);
|
|
4579
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
4580
|
+
return bytes;
|
|
4581
|
+
}
|
|
4582
|
+
return new Uint8Array(Buffer.from(b64, "base64"));
|
|
4583
|
+
}
|
|
4584
|
+
function encodeBase64(bytes) {
|
|
4585
|
+
if (typeof btoa === "function") {
|
|
4586
|
+
let binary = "";
|
|
4587
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
4588
|
+
return btoa(binary);
|
|
4589
|
+
}
|
|
4590
|
+
return Buffer.from(bytes).toString("base64");
|
|
4591
|
+
}
|
|
4592
|
+
|
|
4593
|
+
//#endregion
|
|
4594
|
+
//#region src/modules/crdt/index.ts
|
|
4595
|
+
/**
|
|
4596
|
+
* CrdtManager manages active CrdtField instances and their sync channels.
|
|
4597
|
+
*
|
|
4598
|
+
* Collaborative state lives in two dedicated tables (defined in
|
|
4599
|
+
* `apps/cli/src/meta_tables_remote.surql`):
|
|
4600
|
+
* - `_00_crdt` { record_id, field, state } — one row per (record, field)
|
|
4601
|
+
* - `_00_cursor` { record_id, session_id, field, state } — one row per
|
|
4602
|
+
* (record, session, field)
|
|
4603
|
+
*
|
|
4604
|
+
* Splitting them off the parent row is what makes offline edits mergeable:
|
|
4605
|
+
* each (record, field) gets its own row, so concurrent offline writes don't
|
|
4606
|
+
* collide on the parent's last-write-wins semantics.
|
|
4607
|
+
*
|
|
4608
|
+
* Cross-browser delivery still rides the parent table's existing LIVE feed
|
|
4609
|
+
* to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
|
|
4610
|
+
* (issues 3602, 4026). On every meta UPSERT the writer also bumps the
|
|
4611
|
+
* parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
|
|
4612
|
+
* feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
|
|
4613
|
+
* via subquery. Permission inheritance happens server-side via
|
|
4614
|
+
* `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
|
|
4615
|
+
*/
|
|
4616
|
+
var CrdtManager = class {
|
|
4617
|
+
fields = /* @__PURE__ */ new Map();
|
|
4618
|
+
liveByTable = /* @__PURE__ */ new Map();
|
|
4619
|
+
pendingLive = /* @__PURE__ */ new Map();
|
|
4620
|
+
logger;
|
|
4621
|
+
sessionId = "";
|
|
4622
|
+
constructor(schema, local, remote, logger, debounceMs = 500) {
|
|
4623
|
+
this.schema = schema;
|
|
4624
|
+
this.local = local;
|
|
4625
|
+
this.remote = remote;
|
|
4626
|
+
this.debounceMs = debounceMs;
|
|
4627
|
+
this.logger = logger.child({ service: "CrdtManager" });
|
|
4628
|
+
}
|
|
4629
|
+
/** Set the session id that scopes this client's cursor entries. Must be
|
|
4630
|
+
* called before `open()` for cursors to be pushed under a stable key.
|
|
4631
|
+
* Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
|
|
4632
|
+
* for the data-module salt). */
|
|
4633
|
+
setSessionId(sessionId) {
|
|
4634
|
+
this.sessionId = sessionId;
|
|
4635
|
+
}
|
|
4636
|
+
/**
|
|
4637
|
+
* Open a CRDT field for collaborative editing.
|
|
4638
|
+
*
|
|
4639
|
+
* @param table - Table name
|
|
4640
|
+
* @param recordId - Full record ID (e.g., "thread:abc")
|
|
4641
|
+
* @param field - Field name (e.g., "title", "content")
|
|
4642
|
+
* @param fallbackText - Current plain text from the record, used to seed the
|
|
4643
|
+
* LoroDoc if no CRDT state exists yet (migration path)
|
|
4644
|
+
*/
|
|
4645
|
+
async open(table, recordId, field, fallbackText) {
|
|
4646
|
+
this.assertCrdtField(table, field);
|
|
4647
|
+
const cursorsEnabled = this.fieldHasCursor(table, field);
|
|
4648
|
+
const key = this.makeKey(table, recordId, field);
|
|
4649
|
+
let crdtField = this.fields.get(key);
|
|
4650
|
+
if (crdtField) return crdtField;
|
|
4651
|
+
let initialCrdtState;
|
|
4652
|
+
try {
|
|
4653
|
+
const [result] = await this.local.query(`SELECT VALUE ${field} FROM ONLY $id`, { id: parseRecordIdString(recordId) });
|
|
4654
|
+
const snapshot = this.extractSnapshot(result, cursorsEnabled);
|
|
4655
|
+
if (snapshot) initialCrdtState = snapshot;
|
|
4656
|
+
} catch (e) {
|
|
4657
|
+
this.logger.info({
|
|
4658
|
+
error: String(e),
|
|
4659
|
+
recordId,
|
|
4660
|
+
field,
|
|
4661
|
+
Category: "sp00ky-client::CrdtManager::open"
|
|
4662
|
+
}, "No existing CRDT state found in local cache (continuing with empty doc)");
|
|
4663
|
+
}
|
|
4664
|
+
crdtField = new CrdtField(field, cursorsEnabled, initialCrdtState, this.logger);
|
|
4665
|
+
crdtField.startSync(this.local, this.remote, recordId, this.sessionId, this.debounceMs);
|
|
4666
|
+
this.fields.set(key, crdtField);
|
|
4667
|
+
this.logger.info({
|
|
4668
|
+
key,
|
|
4669
|
+
hasInitialState: !!initialCrdtState,
|
|
4670
|
+
hasFallback: !!fallbackText,
|
|
4671
|
+
Category: "sp00ky-client::CrdtManager::open"
|
|
4672
|
+
}, "CrdtField opened");
|
|
4673
|
+
this.ensureTableSubscription(table);
|
|
4674
|
+
if (!initialCrdtState) this.fetchAndDispatchRow(table, recordId);
|
|
4675
|
+
return crdtField;
|
|
4676
|
+
}
|
|
4677
|
+
close(table, recordId, field) {
|
|
4678
|
+
const key = this.makeKey(table, recordId, field);
|
|
4679
|
+
const crdtField = this.fields.get(key);
|
|
4680
|
+
if (crdtField) {
|
|
4681
|
+
crdtField.stopSync();
|
|
4682
|
+
this.fields.delete(key);
|
|
4683
|
+
}
|
|
4684
|
+
const tablePrefix = `${table}:`;
|
|
4685
|
+
if (!Array.from(this.fields.keys()).some((k) => k.startsWith(tablePrefix))) this.killTableSubscription(table);
|
|
4686
|
+
this.logger.debug({
|
|
4687
|
+
key,
|
|
4688
|
+
Category: "sp00ky-client::CrdtManager::close"
|
|
4689
|
+
}, "CrdtField closed");
|
|
4690
|
+
}
|
|
4691
|
+
closeAll() {
|
|
4692
|
+
for (const [_, field] of this.fields) field.stopSync();
|
|
4693
|
+
this.fields.clear();
|
|
4694
|
+
for (const table of Array.from(this.liveByTable.keys())) this.killTableSubscription(table);
|
|
4695
|
+
}
|
|
4696
|
+
/** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
|
|
4697
|
+
* every open CrdtField on `table`. */
|
|
4698
|
+
async ensureTableSubscription(table) {
|
|
4699
|
+
if (this.liveByTable.has(table)) return;
|
|
4700
|
+
const pending = this.pendingLive.get(table);
|
|
4701
|
+
if (pending) return pending;
|
|
4702
|
+
const start = (async () => {
|
|
4703
|
+
try {
|
|
4704
|
+
const [uuid] = await this.remote.query(`LIVE SELECT * FROM ${table}`);
|
|
4705
|
+
(await this.remote.getClient().liveOf(uuid)).subscribe((message) => {
|
|
4706
|
+
if (message.action === "KILLED") return;
|
|
4707
|
+
if (message.action !== "CREATE" && message.action !== "UPDATE") return;
|
|
4708
|
+
this.dispatchRow(table, message.value);
|
|
4709
|
+
});
|
|
4710
|
+
this.liveByTable.set(table, uuid);
|
|
4711
|
+
this.logger.info({
|
|
4712
|
+
table,
|
|
4713
|
+
Category: "sp00ky-client::CrdtManager::ensureTableSubscription"
|
|
4714
|
+
}, "LIVE SELECT started");
|
|
4715
|
+
} catch (e) {
|
|
4716
|
+
this.logger.warn({
|
|
4717
|
+
error: e,
|
|
4718
|
+
table,
|
|
4719
|
+
Category: "sp00ky-client::CrdtManager::ensureTableSubscription"
|
|
4720
|
+
}, "Failed to start LIVE SELECT");
|
|
4721
|
+
}
|
|
4722
|
+
})();
|
|
4723
|
+
this.pendingLive.set(table, start);
|
|
4724
|
+
try {
|
|
4725
|
+
await start;
|
|
4726
|
+
} finally {
|
|
4727
|
+
this.pendingLive.delete(table);
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4730
|
+
/** Apply a parent-row payload from a non-LIVE source (e.g. the
|
|
4731
|
+
* list_ref-driven sync engine, when the cross-user LIVE on the
|
|
4732
|
+
* parent table is filtered out by the SurrealDB cross-session
|
|
4733
|
+
* permission gap). Same semantics as the internal `dispatchRow`. */
|
|
4734
|
+
applyRow(table, row) {
|
|
4735
|
+
this.dispatchRow(table, row);
|
|
4736
|
+
}
|
|
4737
|
+
/** Dispatch a parent-row LIVE event to every open CrdtField on that
|
|
4738
|
+
* record. Each open field reads its slice of the row directly — the
|
|
4739
|
+
* CRDT snapshot is a column on the parent now, so there is no
|
|
4740
|
+
* follow-up subquery. */
|
|
4741
|
+
dispatchRow(table, row) {
|
|
4742
|
+
const id = row.id != null ? String(row.id) : "";
|
|
4743
|
+
if (!id) return;
|
|
4744
|
+
const rowKeyPrefix = `${table}:${id}:`;
|
|
4745
|
+
for (const [key, crdtField] of this.fields) {
|
|
4746
|
+
if (!key.startsWith(rowKeyPrefix)) continue;
|
|
4747
|
+
const fieldName = key.slice(rowKeyPrefix.length);
|
|
4748
|
+
const cursorsEnabled = this.fieldHasCursor(table, fieldName);
|
|
4749
|
+
const slice = row[fieldName];
|
|
4750
|
+
const snapshot = this.extractSnapshot(slice, cursorsEnabled);
|
|
4751
|
+
if (snapshot) crdtField.importRemote(snapshot);
|
|
4752
|
+
if (cursorsEnabled && slice && typeof slice === "object") {
|
|
4753
|
+
const cursors = slice.cursors;
|
|
4754
|
+
if (cursors && typeof cursors === "object") for (const [sid, blob] of Object.entries(cursors)) {
|
|
4755
|
+
if (sid === this.sessionId) continue;
|
|
4756
|
+
if (typeof blob === "string" && blob.length > 0) crdtField.importRemoteCursor(blob);
|
|
4757
|
+
}
|
|
4758
|
+
}
|
|
4759
|
+
}
|
|
4760
|
+
}
|
|
4761
|
+
/** One-shot remote fetch for a row whose CRDT field hasn't synced
|
|
4762
|
+
* locally yet (fresh device, memory-backed local DB after reload, …).
|
|
4763
|
+
* Used by `open()` when the local read came up empty. Subsequent
|
|
4764
|
+
* cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
|
|
4765
|
+
async fetchAndDispatchRow(table, id) {
|
|
4766
|
+
try {
|
|
4767
|
+
const recordId = parseRecordIdString(id);
|
|
4768
|
+
const [row] = await this.remote.query(`SELECT * FROM ONLY $id`, { id: recordId });
|
|
4769
|
+
if (!row || typeof row !== "object") return;
|
|
4770
|
+
this.dispatchRow(table, row);
|
|
4771
|
+
} catch (e) {
|
|
4772
|
+
this.logger.warn({
|
|
4773
|
+
error: e,
|
|
4774
|
+
table,
|
|
4775
|
+
id,
|
|
4776
|
+
Category: "sp00ky-client::CrdtManager::fetchAndDispatchRow"
|
|
4777
|
+
}, "Failed to fetch parent row for CRDT hydration");
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
/** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
|
|
4781
|
+
* Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
|
|
4782
|
+
fieldHasCursor(table, field) {
|
|
4783
|
+
return !!this.schema.tables.find((t) => t.name === table)?.columns[field]?.cursor;
|
|
4784
|
+
}
|
|
4785
|
+
/** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
|
|
4786
|
+
* the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
|
|
4787
|
+
* `{ state, cursors }` where `state` carries the snapshot bytes. */
|
|
4788
|
+
extractSnapshot(value, cursorsEnabled) {
|
|
4789
|
+
const asBytes = (v) => {
|
|
4790
|
+
if (v instanceof Uint8Array) return v.length > 0 ? v : void 0;
|
|
4791
|
+
if (v instanceof ArrayBuffer) return new Uint8Array(v);
|
|
4792
|
+
if (ArrayBuffer.isView(v)) {
|
|
4793
|
+
const view = v;
|
|
4794
|
+
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
4795
|
+
}
|
|
4796
|
+
if (Array.isArray(v) && v.length > 0 && v.every((n) => typeof n === "number")) return Uint8Array.from(v);
|
|
4797
|
+
};
|
|
4798
|
+
if (cursorsEnabled) {
|
|
4799
|
+
if (value && typeof value === "object" && !(value instanceof Uint8Array)) return asBytes(value.state);
|
|
4800
|
+
return;
|
|
4801
|
+
}
|
|
4802
|
+
return asBytes(value);
|
|
4803
|
+
}
|
|
4804
|
+
killTableSubscription(table) {
|
|
4805
|
+
const uuid = this.liveByTable.get(table);
|
|
4806
|
+
if (uuid) {
|
|
4807
|
+
this.remote.query("KILL $uuid", { uuid }).catch((err) => {
|
|
4808
|
+
this.logger.debug({
|
|
4809
|
+
err,
|
|
4810
|
+
table,
|
|
4811
|
+
Category: "sp00ky-client::CrdtManager::killTableSubscription"
|
|
4812
|
+
}, "KILL of table LIVE failed (already closed?)");
|
|
4813
|
+
});
|
|
4814
|
+
this.liveByTable.delete(table);
|
|
4815
|
+
}
|
|
4816
|
+
}
|
|
4817
|
+
makeKey(table, recordId, field) {
|
|
4818
|
+
return `${table}:${recordId}:${field}`;
|
|
4819
|
+
}
|
|
4820
|
+
/**
|
|
4821
|
+
* Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
|
|
4822
|
+
* typos, removed annotations, and stale schema codegen at the call site instead
|
|
4823
|
+
* of silently producing a non-CRDT writer.
|
|
4824
|
+
*/
|
|
4825
|
+
assertCrdtField(table, field) {
|
|
4826
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(field)) throw new Error(`openCrdtField: refusing unsafe field identifier '${field}' — must match [a-zA-Z_][a-zA-Z0-9_]*`);
|
|
4827
|
+
const tableSchema = this.schema.tables.find((t) => t.name === table);
|
|
4828
|
+
if (!tableSchema) throw new Error(`openCrdtField: unknown table '${table}'. Available: ${this.schema.tables.map((t) => t.name).join(", ")}`);
|
|
4829
|
+
const column = tableSchema.columns[field];
|
|
4830
|
+
if (!column) throw new Error(`openCrdtField: '${table}.${field}' is not in the schema. Available fields: ${Object.keys(tableSchema.columns).join(", ")}`);
|
|
4831
|
+
if (!column.crdt) throw new Error(`openCrdtField: '${table}.${field}' is not annotated '@crdt' in the schema. Add '-- @crdt text' above the field's DEFINE FIELD and regenerate the client schema.`);
|
|
4832
|
+
}
|
|
4833
|
+
};
|
|
4834
|
+
|
|
4835
|
+
//#endregion
|
|
4836
|
+
//#region src/modules/feature-flag/index.ts
|
|
4837
|
+
const FEATURE_QUERY = "SELECT key, variant, payload FROM _00_user_feature WHERE key = $key";
|
|
4838
|
+
var FeatureFlagHandle = class {
|
|
4839
|
+
latest = {
|
|
4840
|
+
variant: void 0,
|
|
4841
|
+
payload: void 0
|
|
4842
|
+
};
|
|
4843
|
+
listeners = /* @__PURE__ */ new Set();
|
|
4844
|
+
unsubscribeFn = null;
|
|
4845
|
+
onCloseFn = null;
|
|
4846
|
+
closed = false;
|
|
4847
|
+
constructor(key, fallback) {
|
|
4848
|
+
this.key = key;
|
|
4849
|
+
this.fallback = fallback;
|
|
4850
|
+
}
|
|
4851
|
+
attach(unsubscribe) {
|
|
4852
|
+
this.unsubscribeFn?.();
|
|
4853
|
+
this.unsubscribeFn = unsubscribe;
|
|
4854
|
+
}
|
|
4855
|
+
detach() {
|
|
4856
|
+
this.unsubscribeFn?.();
|
|
4857
|
+
this.unsubscribeFn = null;
|
|
4858
|
+
}
|
|
4859
|
+
set(snapshot) {
|
|
4860
|
+
if (this.closed) return;
|
|
4861
|
+
this.latest = snapshot;
|
|
4862
|
+
for (const cb of this.listeners) cb(snapshot);
|
|
4863
|
+
}
|
|
4864
|
+
variant() {
|
|
4865
|
+
return this.latest.variant ?? this.fallback;
|
|
4866
|
+
}
|
|
4867
|
+
payload() {
|
|
4868
|
+
return this.latest.payload;
|
|
4869
|
+
}
|
|
4870
|
+
enabled() {
|
|
4871
|
+
const v = this.variant();
|
|
4872
|
+
return v !== void 0 && v !== "off";
|
|
4873
|
+
}
|
|
4874
|
+
subscribe(cb) {
|
|
4875
|
+
this.listeners.add(cb);
|
|
4876
|
+
cb({
|
|
4877
|
+
variant: this.variant(),
|
|
4878
|
+
payload: this.latest.payload
|
|
4879
|
+
});
|
|
4880
|
+
return () => {
|
|
4881
|
+
this.listeners.delete(cb);
|
|
4882
|
+
};
|
|
4883
|
+
}
|
|
4884
|
+
onClose(cb) {
|
|
4885
|
+
this.onCloseFn = cb;
|
|
4886
|
+
}
|
|
4887
|
+
close() {
|
|
4888
|
+
if (this.closed) return;
|
|
4889
|
+
this.closed = true;
|
|
4890
|
+
this.listeners.clear();
|
|
4891
|
+
this.detach();
|
|
4892
|
+
this.onCloseFn?.();
|
|
4893
|
+
}
|
|
4894
|
+
};
|
|
4895
|
+
var FeatureFlagModule = class {
|
|
4896
|
+
logger;
|
|
4897
|
+
active = /* @__PURE__ */ new Set();
|
|
4898
|
+
authUnsubscribe = null;
|
|
4899
|
+
lastUserId = null;
|
|
4900
|
+
constructor(deps) {
|
|
4901
|
+
this.deps = deps;
|
|
4902
|
+
this.logger = deps.logger.child({ service: "FeatureFlagModule" });
|
|
4903
|
+
}
|
|
4904
|
+
init() {
|
|
4905
|
+
if (this.authUnsubscribe) return;
|
|
4906
|
+
this.authUnsubscribe = this.deps.auth.subscribe((userId) => {
|
|
4907
|
+
if (userId === this.lastUserId) return;
|
|
4908
|
+
this.lastUserId = userId;
|
|
4909
|
+
this.refreshAll();
|
|
4910
|
+
});
|
|
4911
|
+
}
|
|
4912
|
+
feature(key, options = {}) {
|
|
4913
|
+
const handle = new FeatureFlagHandle(key, options.fallback);
|
|
4914
|
+
const entry = {
|
|
4915
|
+
handle,
|
|
4916
|
+
ttl: options.ttl ?? "10m"
|
|
4917
|
+
};
|
|
4918
|
+
this.active.add(entry);
|
|
4919
|
+
handle.onClose(() => this.active.delete(entry));
|
|
4920
|
+
this.register(entry);
|
|
4921
|
+
return handle;
|
|
4922
|
+
}
|
|
4923
|
+
async closeAll() {
|
|
4924
|
+
this.authUnsubscribe?.();
|
|
4925
|
+
this.authUnsubscribe = null;
|
|
4926
|
+
for (const entry of [...this.active]) entry.handle.close();
|
|
4927
|
+
}
|
|
4928
|
+
async refreshAll() {
|
|
4929
|
+
for (const entry of this.active) {
|
|
4930
|
+
entry.handle.detach();
|
|
4931
|
+
entry.handle.set({
|
|
4932
|
+
variant: void 0,
|
|
4933
|
+
payload: void 0
|
|
4934
|
+
});
|
|
4935
|
+
await this.register(entry);
|
|
4936
|
+
}
|
|
4937
|
+
}
|
|
4938
|
+
async register(entry) {
|
|
4939
|
+
const { handle, ttl } = entry;
|
|
4940
|
+
try {
|
|
4941
|
+
const hash = await this.deps.dataModule.query("_00_user_feature", FEATURE_QUERY, { key: handle.key }, ttl);
|
|
4942
|
+
this.deps.sync.enqueueDownEvent({
|
|
4943
|
+
type: "register",
|
|
4944
|
+
payload: { hash }
|
|
4945
|
+
});
|
|
4946
|
+
const unsub = this.deps.dataModule.subscribe(hash, (records) => {
|
|
4947
|
+
const row = records[0];
|
|
4948
|
+
handle.set({
|
|
4949
|
+
variant: row?.variant,
|
|
4950
|
+
payload: row?.payload
|
|
4951
|
+
});
|
|
4952
|
+
}, { immediate: true });
|
|
4953
|
+
handle.attach(unsub);
|
|
4954
|
+
} catch (err) {
|
|
4955
|
+
this.logger.warn({
|
|
4956
|
+
err,
|
|
4957
|
+
key: handle.key,
|
|
4958
|
+
Category: "sp00ky-client::FeatureFlagModule::register"
|
|
4959
|
+
}, "Failed to register feature flag query");
|
|
4960
|
+
}
|
|
4961
|
+
}
|
|
4962
|
+
};
|
|
4963
|
+
|
|
2901
4964
|
//#endregion
|
|
2902
4965
|
//#region src/services/persistence/localstorage.ts
|
|
2903
4966
|
var LocalStoragePersistenceClient = class {
|
|
@@ -2930,7 +4993,7 @@ var SurrealDBPersistenceClient = class {
|
|
|
2930
4993
|
}
|
|
2931
4994
|
async set(key, val) {
|
|
2932
4995
|
try {
|
|
2933
|
-
const id = parseRecordIdString(`
|
|
4996
|
+
const id = parseRecordIdString(`_00_kv:${key}`);
|
|
2934
4997
|
await this.db.query(surql.seal(surql.upsert("id", "data")), {
|
|
2935
4998
|
id,
|
|
2936
4999
|
data: { val }
|
|
@@ -2938,40 +5001,75 @@ var SurrealDBPersistenceClient = class {
|
|
|
2938
5001
|
} catch (error) {
|
|
2939
5002
|
this.logger.error({
|
|
2940
5003
|
error,
|
|
2941
|
-
Category: "
|
|
5004
|
+
Category: "sp00ky-client::SurrealDBPersistenceClient::set"
|
|
2942
5005
|
}, "Failed to set KV");
|
|
2943
5006
|
throw error;
|
|
2944
5007
|
}
|
|
2945
5008
|
}
|
|
2946
5009
|
async get(key) {
|
|
2947
5010
|
try {
|
|
2948
|
-
const id = parseRecordIdString(`
|
|
5011
|
+
const id = parseRecordIdString(`_00_kv:${key}`);
|
|
2949
5012
|
const [result] = await this.db.query(surql.seal(surql.selectById("id", ["val"])), { id });
|
|
2950
5013
|
if (!result?.val) return null;
|
|
2951
5014
|
return result.val;
|
|
2952
5015
|
} catch (error) {
|
|
2953
5016
|
this.logger.warn({
|
|
2954
5017
|
error,
|
|
2955
|
-
Category: "
|
|
5018
|
+
Category: "sp00ky-client::SurrealDBPersistenceClient::get"
|
|
2956
5019
|
}, "Failed to get KV");
|
|
2957
5020
|
return null;
|
|
2958
5021
|
}
|
|
2959
5022
|
}
|
|
2960
5023
|
async remove(key) {
|
|
2961
5024
|
try {
|
|
2962
|
-
const id = parseRecordIdString(`
|
|
5025
|
+
const id = parseRecordIdString(`_00_kv:${key}`);
|
|
2963
5026
|
await this.db.query(surql.seal(surql.delete("id")), { id });
|
|
2964
5027
|
} catch (err) {
|
|
2965
5028
|
this.logger.info({
|
|
2966
5029
|
err,
|
|
2967
|
-
Category: "
|
|
5030
|
+
Category: "sp00ky-client::SurrealDBPersistenceClient::remove"
|
|
2968
5031
|
}, "Failed to delete KV");
|
|
2969
5032
|
}
|
|
2970
5033
|
}
|
|
2971
5034
|
};
|
|
2972
5035
|
|
|
2973
5036
|
//#endregion
|
|
2974
|
-
//#region src/
|
|
5037
|
+
//#region src/services/persistence/resilient.ts
|
|
5038
|
+
var ResilientPersistenceClient = class {
|
|
5039
|
+
logger;
|
|
5040
|
+
constructor(inner, logger) {
|
|
5041
|
+
this.inner = inner;
|
|
5042
|
+
this.logger = logger.child({ service: "ResilientPersistenceClient" });
|
|
5043
|
+
}
|
|
5044
|
+
set(key, value) {
|
|
5045
|
+
return this.inner.set(key, value);
|
|
5046
|
+
}
|
|
5047
|
+
async get(key) {
|
|
5048
|
+
try {
|
|
5049
|
+
return await this.inner.get(key);
|
|
5050
|
+
} catch (e) {
|
|
5051
|
+
this.logger.warn({
|
|
5052
|
+
key,
|
|
5053
|
+
error: e,
|
|
5054
|
+
Category: "sp00ky-client::ResilientPersistenceClient::get"
|
|
5055
|
+
}, "Persistence read failed, dropping key");
|
|
5056
|
+
await this.inner.remove(key).catch((removeErr) => {
|
|
5057
|
+
this.logger.debug({
|
|
5058
|
+
key,
|
|
5059
|
+
error: removeErr,
|
|
5060
|
+
Category: "sp00ky-client::ResilientPersistenceClient::get"
|
|
5061
|
+
}, "Failed to drop corrupt persistence key");
|
|
5062
|
+
});
|
|
5063
|
+
return null;
|
|
5064
|
+
}
|
|
5065
|
+
}
|
|
5066
|
+
remove(key) {
|
|
5067
|
+
return this.inner.remove(key);
|
|
5068
|
+
}
|
|
5069
|
+
};
|
|
5070
|
+
|
|
5071
|
+
//#endregion
|
|
5072
|
+
//#region src/sp00ky.ts
|
|
2975
5073
|
var BucketHandle = class {
|
|
2976
5074
|
constructor(bucketName, remote) {
|
|
2977
5075
|
this.bucketName = bucketName;
|
|
@@ -3007,7 +5105,7 @@ var BucketHandle = class {
|
|
|
3007
5105
|
return result;
|
|
3008
5106
|
}
|
|
3009
5107
|
};
|
|
3010
|
-
var
|
|
5108
|
+
var Sp00kyClient = class {
|
|
3011
5109
|
local;
|
|
3012
5110
|
remote;
|
|
3013
5111
|
persistenceClient;
|
|
@@ -3016,6 +5114,8 @@ var SpookyClient = class {
|
|
|
3016
5114
|
dataModule;
|
|
3017
5115
|
sync;
|
|
3018
5116
|
devTools;
|
|
5117
|
+
crdtManager;
|
|
5118
|
+
featureFlags;
|
|
3019
5119
|
logger;
|
|
3020
5120
|
auth;
|
|
3021
5121
|
streamProcessor;
|
|
@@ -3028,33 +5128,49 @@ var SpookyClient = class {
|
|
|
3028
5128
|
get pendingMutationCount() {
|
|
3029
5129
|
return this.sync.pendingMutationCount;
|
|
3030
5130
|
}
|
|
5131
|
+
/** Number of times the initial list_ref LIVE subscription retried on
|
|
5132
|
+
* the most recent `setCurrentUserId` call. 0 when the SSP's
|
|
5133
|
+
* pre-emptive user-table creation got there first; >0 when LIVE
|
|
5134
|
+
* registration hit a "table not found" race. Exposed so the e2e
|
|
5135
|
+
* suite can guard the pre-emptive path against regression. */
|
|
5136
|
+
get liveRetryCount() {
|
|
5137
|
+
return this.sync.liveRetryCount;
|
|
5138
|
+
}
|
|
3031
5139
|
subscribeToPendingMutations(cb) {
|
|
3032
5140
|
return this.sync.subscribeToPendingMutations(cb);
|
|
3033
5141
|
}
|
|
3034
5142
|
constructor(config) {
|
|
3035
5143
|
this.config = config;
|
|
3036
|
-
const logger = createLogger(config.logLevel ?? "info", config.
|
|
3037
|
-
this.logger = logger.child({ service: "
|
|
5144
|
+
const logger = createLogger(config.logLevel ?? "info", config.otelTransmit);
|
|
5145
|
+
this.logger = logger.child({ service: "Sp00kyClient" });
|
|
3038
5146
|
this.logger.info({
|
|
3039
5147
|
config: {
|
|
3040
5148
|
...config,
|
|
3041
5149
|
schema: "[SchemaStructure]"
|
|
3042
5150
|
},
|
|
3043
|
-
Category: "
|
|
3044
|
-
}, "
|
|
5151
|
+
Category: "sp00ky-client::Sp00kyClient::constructor"
|
|
5152
|
+
}, "Sp00kyClient initialized");
|
|
3045
5153
|
this.local = new LocalDatabaseService(this.config.database, logger);
|
|
3046
5154
|
this.remote = new RemoteDatabaseService(this.config.database, logger);
|
|
3047
5155
|
if (config.persistenceClient === "surrealdb") this.persistenceClient = new SurrealDBPersistenceClient(this.local, logger);
|
|
3048
5156
|
else if (config.persistenceClient === "localstorage" || !config.persistenceClient) this.persistenceClient = new LocalStoragePersistenceClient(logger);
|
|
3049
5157
|
else this.persistenceClient = config.persistenceClient;
|
|
5158
|
+
this.persistenceClient = new ResilientPersistenceClient(this.persistenceClient, logger);
|
|
3050
5159
|
this.streamProcessor = new StreamProcessorService(new EventSystem(["stream_update"]), this.local, this.persistenceClient, logger);
|
|
3051
5160
|
this.migrator = new LocalMigrator(this.local, logger);
|
|
3052
5161
|
this.cache = new CacheModule(this.local, this.streamProcessor, (update) => {
|
|
3053
5162
|
this.dataModule.onStreamUpdate(update);
|
|
3054
5163
|
}, logger);
|
|
5164
|
+
this.crdtManager = new CrdtManager(this.config.schema, this.local, this.remote, logger, config.crdtDebounceMs ?? 500);
|
|
3055
5165
|
this.dataModule = new DataModule(this.cache, this.local, this.config.schema, logger, this.config.streamDebounceTime);
|
|
3056
5166
|
this.auth = new AuthService(this.config.schema, this.remote, this.persistenceClient, logger);
|
|
3057
|
-
this.sync = new
|
|
5167
|
+
this.sync = new Sp00kySync(this.local, this.remote, this.cache, this.dataModule, this.config.schema, this.logger, { refSyncIntervalMs: this.config.refSyncIntervalMs });
|
|
5168
|
+
this.featureFlags = new FeatureFlagModule({
|
|
5169
|
+
dataModule: this.dataModule,
|
|
5170
|
+
sync: this.sync,
|
|
5171
|
+
auth: this.auth,
|
|
5172
|
+
logger
|
|
5173
|
+
});
|
|
3058
5174
|
this.devTools = new DevToolsService(this.local, this.remote, logger, this.config.schema, this.auth, this.dataModule);
|
|
3059
5175
|
this.streamProcessor.addReceiver(this.devTools);
|
|
3060
5176
|
this.setupCallbacks();
|
|
@@ -3063,6 +5179,27 @@ var SpookyClient = class {
|
|
|
3063
5179
|
* Setup direct callbacks instead of event subscriptions
|
|
3064
5180
|
*/
|
|
3065
5181
|
setupCallbacks() {
|
|
5182
|
+
this.dataModule.onQueryStatusChange = (queryHash, status) => {
|
|
5183
|
+
this.devTools.logEvent("QUERY_STATUS_CHANGED", {
|
|
5184
|
+
queryHash,
|
|
5185
|
+
status
|
|
5186
|
+
});
|
|
5187
|
+
};
|
|
5188
|
+
this.dataModule.onHeartbeat = (queryHash) => {
|
|
5189
|
+
this.sync.heartbeatQuery(queryHash).catch((err) => {
|
|
5190
|
+
this.logger.warn({
|
|
5191
|
+
err,
|
|
5192
|
+
queryHash,
|
|
5193
|
+
Category: "sp00ky-client::Sp00kyClient::onHeartbeat"
|
|
5194
|
+
}, "TTL heartbeat failed");
|
|
5195
|
+
});
|
|
5196
|
+
};
|
|
5197
|
+
this.dataModule.onDeregister = (queryHash) => {
|
|
5198
|
+
this.sync.enqueueDownEvent({
|
|
5199
|
+
type: "cleanup",
|
|
5200
|
+
payload: { hash: queryHash }
|
|
5201
|
+
});
|
|
5202
|
+
};
|
|
3066
5203
|
this.dataModule.onMutation((mutations) => {
|
|
3067
5204
|
this.devTools.onMutation(mutations);
|
|
3068
5205
|
if (mutations.length > 0) this.sync.enqueueMutation(mutations);
|
|
@@ -3070,6 +5207,22 @@ var SpookyClient = class {
|
|
|
3070
5207
|
this.sync.events.subscribe("SYNC_QUERY_UPDATED", (event) => {
|
|
3071
5208
|
this.devTools.logEvent("SYNC_QUERY_UPDATED", event.payload);
|
|
3072
5209
|
});
|
|
5210
|
+
this.sync.engineEvents.subscribe("SYNC_REMOTE_DATA_INGESTED", (event) => {
|
|
5211
|
+
try {
|
|
5212
|
+
const records = event.payload?.records ?? [];
|
|
5213
|
+
for (const row of records) {
|
|
5214
|
+
const id = row?.id;
|
|
5215
|
+
const table = id && typeof id === "object" && id.table !== void 0 ? String(id.table) : void 0;
|
|
5216
|
+
if (!table) continue;
|
|
5217
|
+
this.crdtManager.applyRow(table, row);
|
|
5218
|
+
}
|
|
5219
|
+
} catch (err) {
|
|
5220
|
+
this.logger.debug({
|
|
5221
|
+
err,
|
|
5222
|
+
Category: "sp00ky-client::engineEvents::ingested"
|
|
5223
|
+
}, "applyRow forwarding from sync ingest failed");
|
|
5224
|
+
}
|
|
5225
|
+
});
|
|
3073
5226
|
this.local.getEvents().subscribe("DATABASE_LOCAL_QUERY", (event) => {
|
|
3074
5227
|
this.devTools.logEvent("LOCAL_QUERY", event.payload);
|
|
3075
5228
|
});
|
|
@@ -3078,44 +5231,90 @@ var SpookyClient = class {
|
|
|
3078
5231
|
});
|
|
3079
5232
|
}
|
|
3080
5233
|
async init() {
|
|
3081
|
-
this.logger.info({ Category: "
|
|
5234
|
+
this.logger.info({ Category: "sp00ky-client::Sp00kyClient::init" }, "Sp00kyClient initialization started");
|
|
3082
5235
|
try {
|
|
3083
|
-
const clientId = this.config.clientId ?? await this.loadOrGenerateClientId();
|
|
3084
|
-
this.persistClientId(clientId);
|
|
3085
|
-
this.logger.debug({
|
|
3086
|
-
clientId,
|
|
3087
|
-
Category: "spooky-client::SpookyClient::init"
|
|
3088
|
-
}, "Client ID loaded");
|
|
3089
5236
|
await this.local.connect();
|
|
3090
|
-
this.logger.debug({ Category: "
|
|
5237
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "Local database connected");
|
|
3091
5238
|
await this.migrator.provision(this.config.schemaSurql);
|
|
3092
|
-
this.logger.debug({ Category: "
|
|
5239
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "Schema provisioned");
|
|
3093
5240
|
await this.remote.connect();
|
|
3094
|
-
this.logger.debug({ Category: "
|
|
5241
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "Remote database connected");
|
|
3095
5242
|
await this.streamProcessor.init();
|
|
3096
|
-
this.
|
|
5243
|
+
this.streamProcessor.setPermissions(extractSelectPermissions(this.config.schemaSurql));
|
|
5244
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "StreamProcessor initialized");
|
|
3097
5245
|
await this.auth.init();
|
|
3098
|
-
this.logger.debug({ Category: "
|
|
3099
|
-
await this.
|
|
3100
|
-
this.
|
|
3101
|
-
|
|
3102
|
-
this.logger.debug({
|
|
3103
|
-
|
|
5246
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "Auth initialized");
|
|
5247
|
+
const sessionId = await this.fetchSessionId();
|
|
5248
|
+
await this.dataModule.init(sessionId);
|
|
5249
|
+
this.crdtManager.setSessionId(sessionId);
|
|
5250
|
+
this.logger.debug({
|
|
5251
|
+
sessionId,
|
|
5252
|
+
Category: "sp00ky-client::Sp00kyClient::init"
|
|
5253
|
+
}, "DataModule initialized");
|
|
5254
|
+
this.auth.subscribe(async (userId) => {
|
|
5255
|
+
this.dataModule.setCurrentUserId(userId);
|
|
5256
|
+
this.streamProcessor.setSessionAuth(this.auth.currentUser?.id ? encodeRecordId(this.auth.currentUser.id) : null, this.auth.access);
|
|
5257
|
+
const next = await this.fetchSessionId();
|
|
5258
|
+
this.dataModule.setSessionId(next);
|
|
5259
|
+
this.crdtManager.setSessionId(next);
|
|
5260
|
+
try {
|
|
5261
|
+
await this.sync.setCurrentUserId(userId);
|
|
5262
|
+
} catch (e) {
|
|
5263
|
+
this.logger.error({
|
|
5264
|
+
error: e,
|
|
5265
|
+
Category: "sp00ky-client::Sp00kyClient::authChange"
|
|
5266
|
+
}, "sync.setCurrentUserId failed");
|
|
5267
|
+
}
|
|
5268
|
+
});
|
|
5269
|
+
await this.sync.init();
|
|
5270
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "Sync initialized");
|
|
5271
|
+
this.featureFlags.init();
|
|
5272
|
+
this.logger.debug({ Category: "sp00ky-client::Sp00kyClient::init" }, "FeatureFlagModule initialized");
|
|
5273
|
+
this.logger.info({ Category: "sp00ky-client::Sp00kyClient::init" }, "Sp00kyClient initialization completed successfully");
|
|
3104
5274
|
} catch (e) {
|
|
3105
5275
|
this.logger.error({
|
|
3106
5276
|
error: e,
|
|
3107
|
-
Category: "
|
|
3108
|
-
}, "
|
|
5277
|
+
Category: "sp00ky-client::Sp00kyClient::init"
|
|
5278
|
+
}, "Sp00kyClient initialization failed");
|
|
3109
5279
|
throw e;
|
|
3110
5280
|
}
|
|
3111
5281
|
}
|
|
3112
5282
|
async close() {
|
|
5283
|
+
await this.featureFlags.closeAll();
|
|
5284
|
+
this.crdtManager.closeAll();
|
|
3113
5285
|
await this.local.close();
|
|
3114
5286
|
await this.remote.close();
|
|
3115
5287
|
}
|
|
5288
|
+
/**
|
|
5289
|
+
* Subscribe to a feature flag for the current user. Returns a
|
|
5290
|
+
* `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
|
|
5291
|
+
* accessors reflect the latest assignment from `_00_user_feature`,
|
|
5292
|
+
* and whose `subscribe(cb)` fires whenever that assignment changes.
|
|
5293
|
+
*
|
|
5294
|
+
* Permissions are enforced by SurrealDB: a client can only ever see
|
|
5295
|
+
* its own row, and cannot create or modify assignments.
|
|
5296
|
+
*/
|
|
5297
|
+
feature(key, options) {
|
|
5298
|
+
return this.featureFlags.feature(key, options);
|
|
5299
|
+
}
|
|
3116
5300
|
authenticate(token) {
|
|
3117
5301
|
return this.remote.getClient().authenticate(token);
|
|
3118
5302
|
}
|
|
5303
|
+
/**
|
|
5304
|
+
* Open a CRDT field for collaborative editing.
|
|
5305
|
+
* Returns a CrdtField with a LoroDoc that can be bound to any editor.
|
|
5306
|
+
* Also starts a LIVE SELECT on the parent table for real-time sync;
|
|
5307
|
+
* incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
|
|
5308
|
+
*/
|
|
5309
|
+
async openCrdtField(table, recordId, field, fallbackText) {
|
|
5310
|
+
return this.crdtManager.open(table, recordId, field, fallbackText);
|
|
5311
|
+
}
|
|
5312
|
+
/**
|
|
5313
|
+
* Close a CRDT field when editing is done.
|
|
5314
|
+
*/
|
|
5315
|
+
closeCrdtField(table, recordId, field) {
|
|
5316
|
+
this.crdtManager.close(table, recordId, field);
|
|
5317
|
+
}
|
|
3119
5318
|
deauthenticate() {
|
|
3120
5319
|
return this.remote.getClient().invalidate();
|
|
3121
5320
|
}
|
|
@@ -3125,7 +5324,18 @@ var SpookyClient = class {
|
|
|
3125
5324
|
async initQuery(table, q, ttl) {
|
|
3126
5325
|
const tableSchema = this.config.schema.tables.find((t) => t.name === table);
|
|
3127
5326
|
if (!tableSchema) throw new Error(`Table ${table} not found`);
|
|
3128
|
-
const
|
|
5327
|
+
const params = parseParams(tableSchema.columns, q.selectQuery.vars ?? {});
|
|
5328
|
+
const hash = await this.dataModule.query(table, q.selectQuery.query, params, ttl);
|
|
5329
|
+
if (this.config.instantHydrate !== false && this.dataModule.isCold(hash)) try {
|
|
5330
|
+
const [rows] = await this.remote.query(q.selectQuery.query, params);
|
|
5331
|
+
await this.dataModule.applyHydration(hash, rows ?? []);
|
|
5332
|
+
} catch (err) {
|
|
5333
|
+
this.logger.warn({
|
|
5334
|
+
err,
|
|
5335
|
+
hash,
|
|
5336
|
+
Category: "sp00ky-client::Sp00kyClient::instantHydrate"
|
|
5337
|
+
}, "Instant hydrate failed; proceeding with registration");
|
|
5338
|
+
}
|
|
3129
5339
|
await this.sync.enqueueDownEvent({
|
|
3130
5340
|
type: "register",
|
|
3131
5341
|
payload: { hash }
|
|
@@ -3139,6 +5349,32 @@ var SpookyClient = class {
|
|
|
3139
5349
|
async subscribe(queryHash, callback, options) {
|
|
3140
5350
|
return this.dataModule.subscribe(queryHash, callback, options);
|
|
3141
5351
|
}
|
|
5352
|
+
/**
|
|
5353
|
+
* Opt-in eager teardown for a query whose last subscriber has gone away
|
|
5354
|
+
* (e.g. a viewport-windowed list cancelling an off-screen window). No-op
|
|
5355
|
+
* while any subscriber remains. Tears down the remote `_00_query` view +
|
|
5356
|
+
* local WASM view instead of waiting for the TTL sweep. Default behavior
|
|
5357
|
+
* (no call here) keeps the view resident for cheap re-subscription.
|
|
5358
|
+
*/
|
|
5359
|
+
deregisterQuery(queryHash) {
|
|
5360
|
+
this.dataModule.deregisterQuery(queryHash);
|
|
5361
|
+
}
|
|
5362
|
+
/**
|
|
5363
|
+
* Subscribe to a query's fetch-status changes (idle/fetching). With
|
|
5364
|
+
* `{ immediate: true }` the callback fires synchronously with the current
|
|
5365
|
+
* status. Powers the `useQuery` hook's `isFetching()` accessor.
|
|
5366
|
+
*/
|
|
5367
|
+
subscribeQueryStatus(queryHash, callback, options) {
|
|
5368
|
+
return this.dataModule.subscribeStatus(queryHash, callback, options);
|
|
5369
|
+
}
|
|
5370
|
+
/**
|
|
5371
|
+
* Report the frontend processing time (ms) a client framework spent applying
|
|
5372
|
+
* an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
|
|
5373
|
+
* surface the "frontend" phase of the per-query timing breakdown.
|
|
5374
|
+
*/
|
|
5375
|
+
reportFrontendTiming(queryHash, ms) {
|
|
5376
|
+
this.dataModule.recordFrontendTiming(queryHash, ms);
|
|
5377
|
+
}
|
|
3142
5378
|
run(backend, path, payload, options) {
|
|
3143
5379
|
return this.dataModule.run(backend, path, payload, options);
|
|
3144
5380
|
}
|
|
@@ -3157,24 +5393,25 @@ var SpookyClient = class {
|
|
|
3157
5393
|
async useRemote(fn) {
|
|
3158
5394
|
return fn(this.remote.getClient());
|
|
3159
5395
|
}
|
|
3160
|
-
|
|
5396
|
+
/**
|
|
5397
|
+
* Fetch SurrealDB's `session::id()` as a string. Used as a salt for
|
|
5398
|
+
* query-id hashing so two sessions for the same user get distinct
|
|
5399
|
+
* `_00_query` rows. Returns empty string if the query fails (we still
|
|
5400
|
+
* boot, just without session scoping for IDs).
|
|
5401
|
+
*/
|
|
5402
|
+
async fetchSessionId() {
|
|
3161
5403
|
try {
|
|
3162
|
-
this.
|
|
5404
|
+
const [sid] = await this.remote.query("RETURN <string>session::id()");
|
|
5405
|
+
return typeof sid === "string" ? sid : "";
|
|
3163
5406
|
} catch (e) {
|
|
3164
5407
|
this.logger.warn({
|
|
3165
5408
|
error: e,
|
|
3166
|
-
Category: "
|
|
3167
|
-
}, "Failed to
|
|
5409
|
+
Category: "sp00ky-client::Sp00kyClient::fetchSessionId"
|
|
5410
|
+
}, "Failed to fetch session::id() — proceeding with empty salt");
|
|
5411
|
+
return "";
|
|
3168
5412
|
}
|
|
3169
5413
|
}
|
|
3170
|
-
async loadOrGenerateClientId() {
|
|
3171
|
-
const clientId = await this.persistenceClient.get("spooky_client_id");
|
|
3172
|
-
if (clientId) return clientId;
|
|
3173
|
-
const newId = generateId();
|
|
3174
|
-
await this.persistClientId(newId);
|
|
3175
|
-
return newId;
|
|
3176
|
-
}
|
|
3177
5414
|
};
|
|
3178
5415
|
|
|
3179
5416
|
//#endregion
|
|
3180
|
-
export { AuthEventTypes, AuthService, BucketHandle,
|
|
5417
|
+
export { AuthEventTypes, AuthService, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, FeatureFlagHandle, FeatureFlagModule, MATERIALIZATION_SAMPLE_WINDOW, Sp00kyClient, createAuthEventSystem, cursorColorFromName, fileToUint8Array, textToHtml };
|