@spooky-sync/core 0.0.1-canary.11 → 0.0.1-canary.110
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 +1033 -372
- package/dist/index.js +5490 -1331
- package/dist/otel/index.d.ts +21 -0
- package/dist/otel/index.js +86 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +107 -0
- package/dist/types.d.ts +721 -0
- package/package.json +40 -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 +77 -32
- package/src/modules/cache/types.ts +2 -2
- package/src/modules/crdt/crdt-field.ts +288 -0
- package/src/modules/crdt/crdt-hydration.test.ts +206 -0
- package/src/modules/crdt/index.ts +357 -0
- package/src/modules/data/data.rebind.test.ts +147 -0
- package/src/modules/data/data.status.test.ts +249 -0
- package/src/modules/data/index.ts +996 -125
- package/src/modules/data/window-query.test.ts +52 -0
- package/src/modules/data/window-query.ts +154 -0
- package/src/modules/devtools/index.ts +180 -28
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +81 -0
- package/src/modules/feature-flag/index.test.ts +120 -0
- package/src/modules/feature-flag/index.ts +209 -0
- package/src/modules/ref-tables.test.ts +91 -0
- package/src/modules/ref-tables.ts +88 -0
- package/src/modules/sync/engine.ts +101 -37
- package/src/modules/sync/events/index.ts +9 -2
- package/src/modules/sync/queue/queue-down.ts +12 -5
- package/src/modules/sync/queue/queue-up.ts +29 -14
- package/src/modules/sync/scheduler.pause.test.ts +109 -0
- package/src/modules/sync/scheduler.ts +73 -7
- package/src/modules/sync/sync.health.test.ts +149 -0
- package/src/modules/sync/sync.ts +1017 -62
- 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/cache-engine.ts +143 -0
- package/src/services/database/database.ts +11 -11
- package/src/services/database/engine-factory.ts +32 -0
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/index.ts +6 -0
- package/src/services/database/local-migrator.ts +27 -27
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +452 -66
- package/src/services/database/plan-render.test.ts +85 -0
- package/src/services/database/plan-render.ts +86 -0
- package/src/services/database/relation-resolver.test.ts +413 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +13 -13
- package/src/services/database/sqlite-cache-engine.test.ts +85 -0
- package/src/services/database/sqlite-cache-engine.ts +693 -0
- package/src/services/database/sqlite-worker.ts +116 -0
- package/src/services/database/surql-translate.ts +291 -0
- package/src/services/database/surreal-cache-engine.ts +122 -0
- 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 +10 -10
- package/src/services/stream-processor/index.ts +295 -38
- 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.reset.test.ts +104 -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 +92 -0
- package/src/sp00ky.ts +795 -0
- package/src/types.ts +231 -15
- package/src/utils/error-classification.test.ts +44 -0
- package/src/utils/error-classification.ts +7 -0
- 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 +64 -1
- package/src/spooky.ts +0 -392
|
@@ -1,28 +1,34 @@
|
|
|
1
1
|
import { RecordId, Duration } from 'surrealdb';
|
|
2
|
-
import {
|
|
2
|
+
import type {
|
|
3
3
|
SchemaStructure,
|
|
4
4
|
TableNames,
|
|
5
5
|
BackendNames,
|
|
6
6
|
BackendRoutes,
|
|
7
7
|
RoutePayload,
|
|
8
|
+
QueryPlan,
|
|
8
9
|
} from '@spooky-sync/query-builder';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
10
|
+
import type { LocalStore } from '../../services/database/index';
|
|
11
|
+
import { StaleEpochError } from '../../services/database/index';
|
|
12
|
+
import type { CacheModule, RecordWithId, CacheRecord } from '../cache/index';
|
|
13
|
+
import type { Logger } from '../../services/logger/index';
|
|
14
|
+
import type { StreamUpdate } from '../../services/stream-processor/index';
|
|
15
|
+
import type {
|
|
15
16
|
QueryConfig,
|
|
16
17
|
QueryHash,
|
|
17
18
|
QueryState,
|
|
19
|
+
QueryStatus,
|
|
20
|
+
QueryStatusCallback,
|
|
18
21
|
QueryTimeToLive,
|
|
19
22
|
QueryUpdateCallback,
|
|
20
23
|
MutationCallback,
|
|
21
24
|
RecordVersionArray,
|
|
22
25
|
QueryConfigRecord,
|
|
23
26
|
UpdateOptions,
|
|
24
|
-
|
|
25
|
-
|
|
27
|
+
QueryTimings,
|
|
28
|
+
PhaseStat,
|
|
29
|
+
RegistrationTimings,
|
|
30
|
+
RunOptions} from '../../types';
|
|
31
|
+
import { MATERIALIZATION_SAMPLE_WINDOW } from '../../types';
|
|
26
32
|
import {
|
|
27
33
|
parseRecordIdString,
|
|
28
34
|
extractIdPart,
|
|
@@ -31,11 +37,29 @@ import {
|
|
|
31
37
|
withRetry,
|
|
32
38
|
surql,
|
|
33
39
|
parseParams,
|
|
40
|
+
cleanRecord,
|
|
34
41
|
extractTablePart,
|
|
35
42
|
generateId,
|
|
36
43
|
} from '../../utils/index';
|
|
37
|
-
import { CreateEvent, DeleteEvent, UpdateEvent } from '../sync/index';
|
|
38
|
-
import { PushEventOptions } from '../../events/index';
|
|
44
|
+
import type { CreateEvent, DeleteEvent, UpdateEvent } from '../sync/index';
|
|
45
|
+
import type { PushEventOptions } from '../../events/index';
|
|
46
|
+
import { buildWindowMaterialization, buildWindowMaterializationPlan } from './window-query';
|
|
47
|
+
|
|
48
|
+
/** Push a timing sample (ms) into a rolling window, capped at the sample window. */
|
|
49
|
+
function pushSample(samples: number[], ms: number): void {
|
|
50
|
+
samples.push(ms);
|
|
51
|
+
if (samples.length > MATERIALIZATION_SAMPLE_WINDOW) samples.shift();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Build a {lastMs,p50,p90,p99,count} summary from a rolling sample window. */
|
|
55
|
+
function phaseStatOf(samples: number[], lastMs: number | null): PhaseStat {
|
|
56
|
+
if (samples.length === 0) {
|
|
57
|
+
return { lastMs, p50: null, p90: null, p99: null, count: 0 };
|
|
58
|
+
}
|
|
59
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
60
|
+
const pick = (q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]!;
|
|
61
|
+
return { lastMs, p50: pick(0.5), p90: pick(0.9), p99: pick(0.99), count: samples.length };
|
|
62
|
+
}
|
|
39
63
|
|
|
40
64
|
/**
|
|
41
65
|
* DataModule - Unified query and mutation management
|
|
@@ -47,22 +71,105 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
47
71
|
private activeQueries: Map<QueryHash, QueryState> = new Map();
|
|
48
72
|
private pendingQueries: Map<QueryHash, Promise<QueryHash>> = new Map();
|
|
49
73
|
private subscriptions: Map<QueryHash, Set<QueryUpdateCallback>> = new Map();
|
|
74
|
+
private statusSubscriptions: Map<QueryHash, Set<QueryStatusCallback>> = new Map();
|
|
50
75
|
private mutationCallbacks: Set<MutationCallback> = new Set();
|
|
51
76
|
private debounceTimers: Map<QueryHash, NodeJS.Timeout> = new Map();
|
|
77
|
+
// The update each debounce timer would process on its trailing edge. Kept in a
|
|
78
|
+
// map (not just the timer closure) so `flushPendingStreamUpdate` can process
|
|
79
|
+
// it early — the sync engine flushes before flipping a query to `idle`, so
|
|
80
|
+
// subscribers never observe idle status with stale (partial-window) rows.
|
|
81
|
+
private pendingStreamUpdates: Map<QueryHash, StreamUpdate> = new Map();
|
|
82
|
+
// Refcount of in-flight fetch cycles per query (registration + concurrent
|
|
83
|
+
// poll/LIVE sync rounds can overlap). Status flips to `fetching` on 0→1 and
|
|
84
|
+
// back to `idle` only on 1→0, so an inner cycle finishing can't emit a
|
|
85
|
+
// premature idle mid-registration.
|
|
86
|
+
private fetchDepth: Map<QueryHash, number> = new Map();
|
|
52
87
|
private logger: Logger;
|
|
88
|
+
/**
|
|
89
|
+
* Optional observer notified whenever a query's fetch status changes.
|
|
90
|
+
* Wired by Sp00kyClient to push status changes into DevTools. Kept as a
|
|
91
|
+
* settable field (rather than a constructor arg) because DevTools is
|
|
92
|
+
* constructed after DataModule.
|
|
93
|
+
*/
|
|
94
|
+
public onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
|
|
95
|
+
/**
|
|
96
|
+
* Optional observer invoked when a still-subscribed query's TTL heartbeat
|
|
97
|
+
* fires (~90% of the TTL). Wired by Sp00kyClient to
|
|
98
|
+
* `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
|
|
99
|
+
* row's `lastActiveAt` so an actively-watched query never expires. Settable
|
|
100
|
+
* field (not a constructor arg) because the sync engine is wired after
|
|
101
|
+
* DataModule is constructed — mirrors `onQueryStatusChange`.
|
|
102
|
+
*/
|
|
103
|
+
public onHeartbeat?: (hash: QueryHash) => void;
|
|
104
|
+
/**
|
|
105
|
+
* Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
|
|
106
|
+
* viewport-windowed list cancelling an off-screen window) loses its last
|
|
107
|
+
* subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
|
|
108
|
+
* tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
|
|
109
|
+
* instead of leaving it for the TTL sweep. The local view + state are freed in
|
|
110
|
+
* {@link finalizeDeregister} only after that remote delete, so a fast
|
|
111
|
+
* re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
|
|
112
|
+
*/
|
|
113
|
+
public onDeregister?: (hash: QueryHash) => void;
|
|
114
|
+
// Salt for query-id hashing. Set from SurrealDB's session::id() so two
|
|
115
|
+
// browser sessions registering the same logical query (same surql + params)
|
|
116
|
+
// don't collide on the same `_00_query` row — each session gets its own.
|
|
117
|
+
// Empty string until init(sessionId) is called.
|
|
118
|
+
private sessionId: string = '';
|
|
119
|
+
// Authenticated user record id (e.g. `"user:abc"`). Updated by
|
|
120
|
+
// `setCurrentUserId` from the auth subscription. null when
|
|
121
|
+
// unauthenticated. Consulted by `Sp00kySync.listRefTable()` so the
|
|
122
|
+
// poll and LIVE subscription target the same per-user
|
|
123
|
+
// `_00_list_ref_user_<id>` table the sync engine writes to.
|
|
124
|
+
private currentUserId: string | null = null;
|
|
53
125
|
|
|
54
126
|
constructor(
|
|
55
127
|
private cache: CacheModule,
|
|
56
|
-
private local:
|
|
128
|
+
private local: LocalStore,
|
|
57
129
|
private schema: S,
|
|
58
130
|
logger: Logger,
|
|
59
|
-
|
|
131
|
+
// Client-side SSP aggregation throttle: coalesces the in-browser
|
|
132
|
+
// StreamProcessor's per-record stream updates per query before notifying
|
|
133
|
+
// readers, so a burst of synced records repaints the UI once per window
|
|
134
|
+
// rather than row-by-row. 50ms keeps it responsive while still batching the
|
|
135
|
+
// initial-sync stream. Override via `SyncedDbConfig.streamDebounceTime`.
|
|
136
|
+
private streamDebounceTime: number = 50
|
|
60
137
|
) {
|
|
61
138
|
this.logger = logger.child({ service: 'DataModule' });
|
|
62
139
|
}
|
|
63
140
|
|
|
64
|
-
async init(): Promise<void> {
|
|
65
|
-
this.
|
|
141
|
+
async init(sessionId: string): Promise<void> {
|
|
142
|
+
this.sessionId = sessionId;
|
|
143
|
+
this.logger.info(
|
|
144
|
+
{ sessionId, Category: 'sp00ky-client::DataModule::init' },
|
|
145
|
+
'DataModule initialized'
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Update the session salt used in query-id hashing. Call this when the
|
|
151
|
+
* SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
|
|
152
|
+
* registered queries will get fresh, session-scoped IDs.
|
|
153
|
+
*/
|
|
154
|
+
setSessionId(sessionId: string): void {
|
|
155
|
+
this.sessionId = sessionId;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Update the authenticated user record id. Pass `null` on sign-out.
|
|
160
|
+
* Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
|
|
161
|
+
* the poll route to the same per-user `_00_list_ref_user_<id>` the
|
|
162
|
+
* SSP writes to.
|
|
163
|
+
*/
|
|
164
|
+
setCurrentUserId(userId: string | null): void {
|
|
165
|
+
this.currentUserId = userId;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Read-only view of the authenticated user id used for per-user
|
|
169
|
+
* `_00_list_ref` routing. Other modules consult this so they pick the
|
|
170
|
+
* same table name DataModule does. */
|
|
171
|
+
getCurrentUserId(): string | null {
|
|
172
|
+
return this.currentUserId;
|
|
66
173
|
}
|
|
67
174
|
|
|
68
175
|
// ==================== QUERY MANAGEMENT ====================
|
|
@@ -74,19 +181,22 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
74
181
|
tableName: T,
|
|
75
182
|
surqlString: string,
|
|
76
183
|
params: Record<string, any>,
|
|
77
|
-
ttl: QueryTimeToLive
|
|
184
|
+
ttl: QueryTimeToLive,
|
|
185
|
+
plan?: QueryPlan
|
|
78
186
|
): Promise<QueryHash> {
|
|
79
187
|
const hash = await this.calculateHash({ surql: surqlString, params });
|
|
80
188
|
this.logger.debug(
|
|
81
|
-
{ hash, Category: '
|
|
189
|
+
{ hash, Category: 'sp00ky-client::DataModule::query' },
|
|
82
190
|
'Query Initialization: started'
|
|
83
191
|
);
|
|
84
192
|
|
|
85
|
-
|
|
193
|
+
// `_00_query` stays the single shared registration table in both
|
|
194
|
+
// ref-modes; the per-user split happens only on `_00_list_ref`.
|
|
195
|
+
const recordId = new RecordId('_00_query', hash);
|
|
86
196
|
|
|
87
197
|
if (this.activeQueries.has(hash)) {
|
|
88
198
|
this.logger.debug(
|
|
89
|
-
{ hash, Category: '
|
|
199
|
+
{ hash, Category: 'sp00ky-client::DataModule::query' },
|
|
90
200
|
'Query Initialization: exists, returning'
|
|
91
201
|
);
|
|
92
202
|
return hash;
|
|
@@ -95,7 +205,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
95
205
|
// Another call is already creating this query — wait for it
|
|
96
206
|
if (this.pendingQueries.has(hash)) {
|
|
97
207
|
this.logger.debug(
|
|
98
|
-
{ hash, Category: '
|
|
208
|
+
{ hash, Category: 'sp00ky-client::DataModule::query' },
|
|
99
209
|
'Query Initialization: pending, waiting for existing creation'
|
|
100
210
|
);
|
|
101
211
|
await this.pendingQueries.get(hash);
|
|
@@ -103,12 +213,12 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
103
213
|
}
|
|
104
214
|
|
|
105
215
|
this.logger.debug(
|
|
106
|
-
{ hash, Category: '
|
|
216
|
+
{ hash, Category: 'sp00ky-client::DataModule::query' },
|
|
107
217
|
'Query Initialization: not found, creating new query'
|
|
108
218
|
);
|
|
109
219
|
|
|
110
220
|
// Create the query and track the pending promise
|
|
111
|
-
const promise = this.createAndRegisterQuery<T>(hash, recordId, surqlString, params, ttl, tableName);
|
|
221
|
+
const promise = this.createAndRegisterQuery<T>(hash, recordId, surqlString, params, ttl, tableName, plan);
|
|
112
222
|
this.pendingQueries.set(hash, promise);
|
|
113
223
|
try {
|
|
114
224
|
await promise;
|
|
@@ -147,11 +257,95 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
147
257
|
subs.delete(callback);
|
|
148
258
|
if (subs.size === 0) {
|
|
149
259
|
this.subscriptions.delete(queryHash);
|
|
260
|
+
// NOTE: intentionally do NOT tear down the query / free its in-browser
|
|
261
|
+
// SSP view here. The subscriber-gated heartbeat (startTTLHeartbeat)
|
|
262
|
+
// already self-stops once subscribers hit 0, so an abandoned query
|
|
263
|
+
// stops being kept alive and the server's TTL sweep removes it. Freeing
|
|
264
|
+
// the local view on every last-unsubscribe caused re-registration churn
|
|
265
|
+
// on navigation (open A → leave → open A again re-registers), which is
|
|
266
|
+
// a flakiness risk for no real benefit — keep the local view resident.
|
|
150
267
|
}
|
|
151
268
|
}
|
|
152
269
|
};
|
|
153
270
|
}
|
|
154
271
|
|
|
272
|
+
/**
|
|
273
|
+
* Subscribe to a query's fetch-status changes (idle/fetching).
|
|
274
|
+
* With `{ immediate: true }` the callback fires synchronously with the
|
|
275
|
+
* current status (defaults to `idle` if the query isn't registered yet).
|
|
276
|
+
*/
|
|
277
|
+
subscribeStatus(
|
|
278
|
+
queryHash: string,
|
|
279
|
+
callback: QueryStatusCallback,
|
|
280
|
+
options: { immediate?: boolean } = {}
|
|
281
|
+
): () => void {
|
|
282
|
+
if (!this.statusSubscriptions.has(queryHash)) {
|
|
283
|
+
this.statusSubscriptions.set(queryHash, new Set());
|
|
284
|
+
}
|
|
285
|
+
this.statusSubscriptions.get(queryHash)?.add(callback);
|
|
286
|
+
|
|
287
|
+
if (options.immediate) {
|
|
288
|
+
callback(this.activeQueries.get(queryHash)?.status ?? 'idle');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
return () => {
|
|
292
|
+
const subs = this.statusSubscriptions.get(queryHash);
|
|
293
|
+
if (subs) {
|
|
294
|
+
subs.delete(callback);
|
|
295
|
+
if (subs.size === 0) {
|
|
296
|
+
this.statusSubscriptions.delete(queryHash);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Set a query's fetch status and notify status observers (DevTools +
|
|
304
|
+
* `subscribeStatus` listeners). No-op when the status is unchanged or the
|
|
305
|
+
* query is unknown.
|
|
306
|
+
*/
|
|
307
|
+
setQueryStatus(queryHash: string, status: QueryStatus): void {
|
|
308
|
+
const queryState = this.activeQueries.get(queryHash);
|
|
309
|
+
if (!queryState || queryState.status === status) {
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
queryState.status = status;
|
|
313
|
+
|
|
314
|
+
this.onQueryStatusChange?.(queryHash, status);
|
|
315
|
+
|
|
316
|
+
const subs = this.statusSubscriptions.get(queryHash);
|
|
317
|
+
if (subs) {
|
|
318
|
+
for (const callback of subs) {
|
|
319
|
+
callback(status);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Enter a fetch cycle for a query. Refcounted: registration and concurrent
|
|
326
|
+
* poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
|
|
327
|
+
* cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
|
|
328
|
+
* emits `idle`. Always pair with `endFetching` in a `finally`.
|
|
329
|
+
*/
|
|
330
|
+
beginFetching(queryHash: string): void {
|
|
331
|
+
const depth = this.fetchDepth.get(queryHash) ?? 0;
|
|
332
|
+
this.fetchDepth.set(queryHash, depth + 1);
|
|
333
|
+
if (depth === 0) {
|
|
334
|
+
this.setQueryStatus(queryHash, 'fetching');
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
|
|
339
|
+
endFetching(queryHash: string): void {
|
|
340
|
+
const depth = this.fetchDepth.get(queryHash) ?? 0;
|
|
341
|
+
if (depth <= 1) {
|
|
342
|
+
this.fetchDepth.delete(queryHash);
|
|
343
|
+
this.setQueryStatus(queryHash, 'idle');
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
this.fetchDepth.set(queryHash, depth - 1);
|
|
347
|
+
}
|
|
348
|
+
|
|
155
349
|
/**
|
|
156
350
|
* Subscribe to mutations (for sync)
|
|
157
351
|
*/
|
|
@@ -168,67 +362,208 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
168
362
|
async onStreamUpdate(update: StreamUpdate): Promise<void> {
|
|
169
363
|
const { queryHash, op } = update;
|
|
170
364
|
|
|
171
|
-
//
|
|
172
|
-
//
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
365
|
+
// DELETE propagates immediately — a removed row should disappear without
|
|
366
|
+
// waiting on a debounce.
|
|
367
|
+
//
|
|
368
|
+
// CREATE and UPDATE are coalesced per query on a trailing timer. A list's
|
|
369
|
+
// rows stream in from sync as many small `_00_list_ref` diffs, each its own
|
|
370
|
+
// `cache.saveBatch` → one stream update per chunk. `ingestMany` only
|
|
371
|
+
// coalesces records ingested synchronously together, so chunks spread over
|
|
372
|
+
// time each re-materialize and re-notify — a 50-row window can fire 30+
|
|
373
|
+
// updates as it fills. Each StreamUpdate carries the full materialized
|
|
374
|
+
// `localArray`, so the latest one already reflects every prior chunk: keep
|
|
375
|
+
// only it and fire once on the trailing edge, settling the query in a couple
|
|
376
|
+
// of notifications instead of one per chunk.
|
|
377
|
+
if (op === 'DELETE') {
|
|
378
|
+
const existing = this.debounceTimers.get(queryHash);
|
|
379
|
+
if (existing) {
|
|
380
|
+
clearTimeout(existing);
|
|
381
|
+
this.debounceTimers.delete(queryHash);
|
|
177
382
|
}
|
|
383
|
+
// The DELETE update carries the full latest localArray, so the coalesced
|
|
384
|
+
// CREATE/UPDATE it supersedes is already reflected — drop it.
|
|
385
|
+
this.pendingStreamUpdates.delete(queryHash);
|
|
386
|
+
await this.processStreamUpdate(update);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
178
389
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
390
|
+
// Clear existing timer if any
|
|
391
|
+
if (this.debounceTimers.has(queryHash)) {
|
|
392
|
+
// oxlint-disable-next-line no-non-null-assertion -- guarded by .has() check above
|
|
393
|
+
clearTimeout(this.debounceTimers.get(queryHash)!);
|
|
394
|
+
}
|
|
184
395
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
396
|
+
// Set new timer
|
|
397
|
+
this.pendingStreamUpdates.set(queryHash, update);
|
|
398
|
+
const timer = setTimeout(async () => {
|
|
399
|
+
this.debounceTimers.delete(queryHash);
|
|
400
|
+
this.pendingStreamUpdates.delete(queryHash);
|
|
188
401
|
await this.processStreamUpdate(update);
|
|
402
|
+
}, this.streamDebounceTime);
|
|
403
|
+
|
|
404
|
+
this.debounceTimers.set(queryHash, timer);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Process a query's pending (debounced) stream update NOW instead of on the
|
|
409
|
+
* trailing edge. Called by the sync engine before it flips a query back to
|
|
410
|
+
* `idle`, so the status change never races ahead of the rows it fetched.
|
|
411
|
+
* No-op when nothing is pending. The pending entry is removed before the
|
|
412
|
+
* await so a concurrently-firing timer can't process it twice.
|
|
413
|
+
*/
|
|
414
|
+
async flushPendingStreamUpdate(queryHash: string): Promise<void> {
|
|
415
|
+
const timer = this.debounceTimers.get(queryHash);
|
|
416
|
+
if (timer) {
|
|
417
|
+
clearTimeout(timer);
|
|
418
|
+
this.debounceTimers.delete(queryHash);
|
|
189
419
|
}
|
|
420
|
+
const pending = this.pendingStreamUpdates.get(queryHash);
|
|
421
|
+
if (!pending) return;
|
|
422
|
+
this.pendingStreamUpdates.delete(queryHash);
|
|
423
|
+
await this.processStreamUpdate(pending);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Materialize a query's result rows from the local DB. For a windowed query
|
|
427
|
+
// (`LIMIT n START m`, m>0) the original surql is NOT re-run — re-applying
|
|
428
|
+
// `START m` against the shared local store would skip the window's own rows
|
|
429
|
+
// (sparse windowing) and return nothing. Instead we select the window's
|
|
430
|
+
// record id-set directly, preferring the server's `list_ref` (`remoteArray`,
|
|
431
|
+
// authoritative) over the in-browser SSP's view (`sspArray`), and re-apply
|
|
432
|
+
// the original ORDER BY for stable order.
|
|
433
|
+
private async materializeRecords(
|
|
434
|
+
queryState: QueryState,
|
|
435
|
+
sspArray?: Array<[string, number]>
|
|
436
|
+
): Promise<Record<string, any>[]> {
|
|
437
|
+
const t0 = performance.now();
|
|
438
|
+
const plan = queryState.config.plan;
|
|
439
|
+
const windowMat = buildWindowMaterialization(queryState.config.surql);
|
|
440
|
+
let records: Record<string, any>[];
|
|
441
|
+
if (windowMat) {
|
|
442
|
+
const win =
|
|
443
|
+
(queryState.config.remoteArray?.length && queryState.config.remoteArray) ||
|
|
444
|
+
(sspArray?.length && sspArray) ||
|
|
445
|
+
queryState.config.localArray ||
|
|
446
|
+
[];
|
|
447
|
+
const winIds = win.map(([id]) => parseRecordIdString(id));
|
|
448
|
+
if (plan) {
|
|
449
|
+
// Engine-neutral window materialization: select exactly the id-set,
|
|
450
|
+
// keeping ORDER BY + relations. Works on any local engine.
|
|
451
|
+
const winPlan = buildWindowMaterializationPlan(plan, winIds) ?? { ...plan, ids: winIds };
|
|
452
|
+
records = await this.local.select(winPlan, queryState.config.params);
|
|
453
|
+
} else {
|
|
454
|
+
const [rows] = await this.local.query<[Record<string, any>[]]>(windowMat.query, {
|
|
455
|
+
...queryState.config.params,
|
|
456
|
+
__win: winIds,
|
|
457
|
+
});
|
|
458
|
+
records = rows || [];
|
|
459
|
+
}
|
|
460
|
+
} else if (plan) {
|
|
461
|
+
records = await this.local.select(plan, queryState.config.params);
|
|
462
|
+
} else {
|
|
463
|
+
const [rows] = await this.local.query<[Record<string, any>[]]>(
|
|
464
|
+
queryState.config.surql,
|
|
465
|
+
queryState.config.params
|
|
466
|
+
);
|
|
467
|
+
records = rows || [];
|
|
468
|
+
}
|
|
469
|
+
// Local SurrealDB record-fetch time → DevTools "localFetch" phase.
|
|
470
|
+
this.recordPhase(queryState, 'localFetch', performance.now() - t0);
|
|
471
|
+
return records;
|
|
190
472
|
}
|
|
191
473
|
|
|
192
474
|
private async processStreamUpdate(update: StreamUpdate): Promise<void> {
|
|
193
|
-
const { queryHash, localArray } = update;
|
|
475
|
+
const { queryHash, localArray, materializationTimeMs } = update;
|
|
194
476
|
const queryState = this.activeQueries.get(queryHash);
|
|
195
477
|
if (!queryState) {
|
|
196
478
|
this.logger.warn(
|
|
197
|
-
{ queryHash, Category: '
|
|
479
|
+
{ queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
|
|
198
480
|
'Received update for unknown query. Skipping...'
|
|
199
481
|
);
|
|
200
482
|
return;
|
|
201
483
|
}
|
|
202
484
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
)
|
|
485
|
+
// Update the rolling materialization-sample window before the work that
|
|
486
|
+
// could throw, so the percentiles still move when the downstream local
|
|
487
|
+
// query fails (the materialization step itself ran).
|
|
488
|
+
if (typeof materializationTimeMs === 'number') {
|
|
489
|
+
queryState.materializationSamples.push(materializationTimeMs);
|
|
490
|
+
if (queryState.materializationSamples.length > MATERIALIZATION_SAMPLE_WINDOW) {
|
|
491
|
+
queryState.materializationSamples.shift();
|
|
492
|
+
}
|
|
493
|
+
queryState.lastIngestLatencyMs = materializationTimeMs;
|
|
494
|
+
}
|
|
495
|
+
// Record the SSP internal sub-phase timings (from the WASM binding) so
|
|
496
|
+
// DevTools can attribute ingest cost to store-apply vs circuit-step vs transform.
|
|
497
|
+
if (typeof update.storeApplyMs === 'number')
|
|
498
|
+
this.recordPhase(queryState, 'sspStoreApply', update.storeApplyMs);
|
|
499
|
+
if (typeof update.circuitStepMs === 'number')
|
|
500
|
+
this.recordPhase(queryState, 'sspCircuitStep', update.circuitStepMs);
|
|
501
|
+
if (typeof update.transformMs === 'number')
|
|
502
|
+
this.recordPhase(queryState, 'sspTransform', update.transformMs);
|
|
503
|
+
const percentiles = this.computeMaterializationPercentiles(queryState.materializationSamples);
|
|
504
|
+
|
|
505
|
+
// Fence against bucket switches: this update's `localArray` came from the
|
|
506
|
+
// pre-switch SSP circuit; applying it after a switch would show (and
|
|
507
|
+
// persist) the previous user's ids in the new bucket.
|
|
508
|
+
const epoch = this.local.epoch;
|
|
209
509
|
|
|
210
|
-
|
|
211
|
-
|
|
510
|
+
try {
|
|
511
|
+
// Materialize the query's rows. For a windowed (offset) query, re-running
|
|
512
|
+
// the original surql would re-apply `START n` against the shared local DB
|
|
513
|
+
// and skip the window's rows entirely; instead select the SSP's
|
|
514
|
+
// materialized window id-set (`localArray`) directly, re-applying the
|
|
515
|
+
// original ORDER BY for stable display order. Non-offset queries keep the
|
|
516
|
+
// normal re-query path.
|
|
517
|
+
const newRecords = await this.materializeRecords(queryState, localArray);
|
|
518
|
+
if (epoch !== this.local.epoch) return;
|
|
212
519
|
queryState.config.localArray = localArray;
|
|
213
|
-
await this.local.query(surql.seal(surql.updateSet('id', ['localArray'])), {
|
|
214
|
-
id: queryState.config.id,
|
|
215
|
-
localArray,
|
|
216
|
-
});
|
|
217
520
|
|
|
218
|
-
// Skip notification if records haven't changed
|
|
219
521
|
const prevJson = JSON.stringify(queryState.records);
|
|
220
522
|
const newJson = JSON.stringify(newRecords);
|
|
221
523
|
queryState.records = newRecords;
|
|
222
|
-
|
|
524
|
+
const recordsChanged = prevJson !== newJson;
|
|
525
|
+
|
|
526
|
+
// updateCount counts user-visible updates (matches the prior semantic),
|
|
527
|
+
// while the materialization sample/percentiles already moved above for
|
|
528
|
+
// every observed engine step.
|
|
529
|
+
if (recordsChanged) {
|
|
530
|
+
queryState.updateCount++;
|
|
531
|
+
queryState.lastUpdatedAt = Date.now();
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
await this.local.query(
|
|
535
|
+
surql.seal(
|
|
536
|
+
surql.updateSet('id', [
|
|
537
|
+
'localArray',
|
|
538
|
+
'rowCount',
|
|
539
|
+
'updateCount',
|
|
540
|
+
'lastIngestLatency',
|
|
541
|
+
'materializationP55',
|
|
542
|
+
'materializationP90',
|
|
543
|
+
'materializationP99',
|
|
544
|
+
])
|
|
545
|
+
),
|
|
546
|
+
{
|
|
547
|
+
id: queryState.config.id,
|
|
548
|
+
localArray,
|
|
549
|
+
rowCount: localArray.length,
|
|
550
|
+
updateCount: queryState.updateCount,
|
|
551
|
+
lastIngestLatency: queryState.lastIngestLatencyMs,
|
|
552
|
+
materializationP55: percentiles.p55,
|
|
553
|
+
materializationP90: percentiles.p90,
|
|
554
|
+
materializationP99: percentiles.p99,
|
|
555
|
+
},
|
|
556
|
+
{ epoch }
|
|
557
|
+
);
|
|
558
|
+
|
|
559
|
+
if (!recordsChanged) {
|
|
223
560
|
this.logger.debug(
|
|
224
|
-
{ queryHash, Category: '
|
|
561
|
+
{ queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
|
|
225
562
|
'Query records unchanged, skipping notification'
|
|
226
563
|
);
|
|
227
564
|
return;
|
|
228
565
|
}
|
|
229
566
|
|
|
230
|
-
queryState.updateCount++;
|
|
231
|
-
|
|
232
567
|
// Notify subscribers
|
|
233
568
|
const subscribers = this.subscriptions.get(queryHash);
|
|
234
569
|
if (subscribers) {
|
|
@@ -240,17 +575,108 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
240
575
|
this.logger.debug(
|
|
241
576
|
{
|
|
242
577
|
queryHash,
|
|
243
|
-
recordCount:
|
|
244
|
-
Category: '
|
|
578
|
+
recordCount: newRecords?.length,
|
|
579
|
+
Category: 'sp00ky-client::DataModule::onStreamUpdate',
|
|
245
580
|
},
|
|
246
581
|
'Query updated from stream'
|
|
247
582
|
);
|
|
248
583
|
} catch (err) {
|
|
584
|
+
if (err instanceof StaleEpochError) {
|
|
585
|
+
this.logger.debug(
|
|
586
|
+
{ queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
|
|
587
|
+
'Dropped stream update from before a bucket switch'
|
|
588
|
+
);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
queryState.errorCount++;
|
|
249
592
|
this.logger.error(
|
|
250
|
-
{ err, queryHash, Category: '
|
|
593
|
+
{ err, queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
|
|
251
594
|
'Failed to fetch records for stream update'
|
|
252
595
|
);
|
|
596
|
+
// Best-effort persist of the bumped errorCount; swallow secondary
|
|
597
|
+
// failures to avoid masking the original error in logs.
|
|
598
|
+
try {
|
|
599
|
+
await this.local.query(surql.seal(surql.updateSet('id', ['errorCount'])), {
|
|
600
|
+
id: queryState.config.id,
|
|
601
|
+
errorCount: queryState.errorCount,
|
|
602
|
+
});
|
|
603
|
+
} catch (persistErr) {
|
|
604
|
+
this.logger.warn(
|
|
605
|
+
{
|
|
606
|
+
err: persistErr,
|
|
607
|
+
queryHash,
|
|
608
|
+
Category: 'sp00ky-client::DataModule::onStreamUpdate',
|
|
609
|
+
},
|
|
610
|
+
'Failed to persist incremented errorCount'
|
|
611
|
+
);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* Compute p55/p90/p99 from a rolling window of materialization samples.
|
|
618
|
+
* Returns nulls for any percentile that has no samples yet so SurrealDB
|
|
619
|
+
* `option<float>` columns stay NONE rather than 0 before the first ingest.
|
|
620
|
+
*/
|
|
621
|
+
private computeMaterializationPercentiles(samples: number[]): {
|
|
622
|
+
p55: number | null;
|
|
623
|
+
p90: number | null;
|
|
624
|
+
p99: number | null;
|
|
625
|
+
} {
|
|
626
|
+
if (samples.length === 0) {
|
|
627
|
+
return { p55: null, p90: null, p99: null };
|
|
253
628
|
}
|
|
629
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
630
|
+
const pick = (q: number) => {
|
|
631
|
+
const idx = Math.min(sorted.length - 1, Math.floor(q * sorted.length));
|
|
632
|
+
return sorted[idx]!;
|
|
633
|
+
};
|
|
634
|
+
return { p55: pick(0.55), p90: pick(0.90), p99: pick(0.99) };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Record a per-phase timing sample (ms) on a query's rolling window. */
|
|
638
|
+
private recordPhase(qs: QueryState, phase: string, ms: number): void {
|
|
639
|
+
if (!Number.isFinite(ms)) return;
|
|
640
|
+
const arr = qs.phaseSamples[phase] ?? (qs.phaseSamples[phase] = []);
|
|
641
|
+
pushSample(arr, ms);
|
|
642
|
+
qs.phaseLast[phase] = ms;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
|
|
646
|
+
recordRemoteFetch(hash: string, ms: number): void {
|
|
647
|
+
const qs = this.activeQueries.get(hash);
|
|
648
|
+
if (qs) this.recordPhase(qs, 'remoteFetch', ms);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Record the frontend reconcile time (ms) for a query. Called from `useQuery`
|
|
653
|
+
* via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
|
|
654
|
+
*/
|
|
655
|
+
recordFrontendTiming(hash: string, ms: number): void {
|
|
656
|
+
const qs = this.activeQueries.get(hash);
|
|
657
|
+
if (qs) this.recordPhase(qs, 'frontend', ms);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Build the per-query processing-time breakdown surfaced to the DevTools panel
|
|
662
|
+
* and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
|
|
663
|
+
* the rest come from the per-phase rolling windows + one-shot registration timings.
|
|
664
|
+
*/
|
|
665
|
+
phaseTimings(q: QueryState): QueryTimings {
|
|
666
|
+
const stat = (phase: string) =>
|
|
667
|
+
phaseStatOf(q.phaseSamples[phase] ?? [], q.phaseLast[phase] ?? null);
|
|
668
|
+
return {
|
|
669
|
+
ssp: phaseStatOf(q.materializationSamples, q.lastIngestLatencyMs),
|
|
670
|
+
sspStoreApply: stat('sspStoreApply'),
|
|
671
|
+
sspCircuitStep: stat('sspCircuitStep'),
|
|
672
|
+
sspTransform: stat('sspTransform'),
|
|
673
|
+
localFetch: stat('localFetch'),
|
|
674
|
+
remoteFetch: stat('remoteFetch'),
|
|
675
|
+
frontend: stat('frontend'),
|
|
676
|
+
registration: q.registrationTimings,
|
|
677
|
+
updateCount: q.updateCount,
|
|
678
|
+
errorCount: q.errorCount,
|
|
679
|
+
};
|
|
254
680
|
}
|
|
255
681
|
|
|
256
682
|
/**
|
|
@@ -260,6 +686,164 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
260
686
|
return this.activeQueries.get(hash);
|
|
261
687
|
}
|
|
262
688
|
|
|
689
|
+
/**
|
|
690
|
+
* Cold-query guard for instant-hydrate: true when the query exists, hasn't been
|
|
691
|
+
* hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
|
|
692
|
+
* We gate on `remoteArray`, not local `records`: a windowed query is often
|
|
693
|
+
* partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
|
|
694
|
+
* but it still hasn't loaded its own full window from the server — so it should
|
|
695
|
+
* still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
|
|
696
|
+
*/
|
|
697
|
+
isCold(hash: string): boolean {
|
|
698
|
+
const qs = this.activeQueries.get(hash);
|
|
699
|
+
return !!qs && !qs.hydrated && (qs.config.remoteArray?.length ?? 0) === 0;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Walk a hydrated record's fields and append any EMBEDDED child records to
|
|
704
|
+
* `batch` (recursing for nested related fields). An embedded child is a
|
|
705
|
+
* value that is itself a record — a non-null object whose `id` is a
|
|
706
|
+
* `RecordId` — or an array of such records (one-to-many vs one-to-one). A
|
|
707
|
+
* bare `RecordId` (a foreign-key reference) or any other value is skipped,
|
|
708
|
+
* so this never mistakes a FK column for an embedded body. Children are
|
|
709
|
+
* keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
|
|
710
|
+
* to their table's real columns (which strips the alias/related fields).
|
|
711
|
+
* `seen` dedupes within the batch.
|
|
712
|
+
*/
|
|
713
|
+
private collectEmbeddedChildren(
|
|
714
|
+
record: Record<string, any>,
|
|
715
|
+
batch: CacheRecord[],
|
|
716
|
+
seen: Set<string>
|
|
717
|
+
): void {
|
|
718
|
+
const isEmbeddedRecord = (v: unknown): v is RecordWithId =>
|
|
719
|
+
!!v &&
|
|
720
|
+
typeof v === 'object' &&
|
|
721
|
+
!(v instanceof RecordId) &&
|
|
722
|
+
(v as { id?: unknown }).id instanceof RecordId;
|
|
723
|
+
|
|
724
|
+
for (const value of Object.values(record)) {
|
|
725
|
+
const children = Array.isArray(value)
|
|
726
|
+
? value.filter(isEmbeddedRecord)
|
|
727
|
+
: isEmbeddedRecord(value)
|
|
728
|
+
? [value]
|
|
729
|
+
: [];
|
|
730
|
+
for (const child of children) {
|
|
731
|
+
const key = encodeRecordId(child.id);
|
|
732
|
+
if (seen.has(key)) continue;
|
|
733
|
+
seen.add(key);
|
|
734
|
+
// Recurse FIRST so nested grandchildren are captured before `cleanRecord`
|
|
735
|
+
// strips this child's alias fields.
|
|
736
|
+
this.collectEmbeddedChildren(child, batch, seen);
|
|
737
|
+
const table = child.id.table.toString();
|
|
738
|
+
const tableSchema = this.schema.tables.find((t) => t.name === table);
|
|
739
|
+
batch.push({
|
|
740
|
+
table,
|
|
741
|
+
op: 'CREATE',
|
|
742
|
+
record: (tableSchema
|
|
743
|
+
? cleanRecord(tableSchema.columns, child)
|
|
744
|
+
: child) as RecordWithId,
|
|
745
|
+
version: (child._00_rv as number) || 1,
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
|
|
753
|
+
* surql run directly) so the query DISPLAYS immediately, while the full realtime
|
|
754
|
+
* registration proceeds in the background. Ingests with versions (`_00_rv`) so the
|
|
755
|
+
* later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
|
|
756
|
+
* `remoteArray` so windowed queries materialize the correct window (no sparse
|
|
757
|
+
* local-circuit issue). Runs at most once per query (the `hydrated` flag).
|
|
758
|
+
*/
|
|
759
|
+
async applyHydration(hash: string, rows: RecordWithId[]): Promise<void> {
|
|
760
|
+
const queryState = this.activeQueries.get(hash);
|
|
761
|
+
if (!queryState) return;
|
|
762
|
+
queryState.hydrated = true; // run-once, even when the remote returns nothing
|
|
763
|
+
if (rows.length === 0) return;
|
|
764
|
+
|
|
765
|
+
const tableName = queryState.config.tableName;
|
|
766
|
+
const batch: CacheRecord[] = rows.map((record) => ({
|
|
767
|
+
table: tableName,
|
|
768
|
+
op: 'CREATE' as const,
|
|
769
|
+
record,
|
|
770
|
+
version: (record._00_rv as number) || 1,
|
|
771
|
+
}));
|
|
772
|
+
|
|
773
|
+
// Flicker-free related data on cold first paint: a `.related()` query's
|
|
774
|
+
// rows arrive with their child rows EMBEDDED (the correlated subquery,
|
|
775
|
+
// e.g. `(SELECT * FROM comment WHERE game=$parent.id) AS comments`). The
|
|
776
|
+
// primary batch above persists only the parent table, so the immediate
|
|
777
|
+
// `materializeRecords` below would re-run the correlated surql against a
|
|
778
|
+
// local DB with no child rows and overwrite the embedded result with
|
|
779
|
+
// empties. Extract those embedded children (any nesting depth) and
|
|
780
|
+
// persist them as their own records so the re-materialization finds them.
|
|
781
|
+
const seen = new Set<string>(rows.map((r) => encodeRecordId(r.id)));
|
|
782
|
+
for (const record of rows) {
|
|
783
|
+
this.collectEmbeddedChildren(record, batch, seen);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
await this.cache.saveBatch(batch);
|
|
787
|
+
|
|
788
|
+
// Prime remoteArray from the hydrated id+version pairs: `materializeRecords`
|
|
789
|
+
// prefers it for windowed queries (correct window) and it feeds the version
|
|
790
|
+
// dedup. Registration later overwrites it with the authoritative `_00_list_ref`.
|
|
791
|
+
queryState.config.remoteArray = rows.map(
|
|
792
|
+
(r) => [encodeRecordId(r.id), (r._00_rv as number) || 1] as [string, number]
|
|
793
|
+
);
|
|
794
|
+
|
|
795
|
+
queryState.records = await this.materializeRecords(queryState);
|
|
796
|
+
const subscribers = this.subscriptions.get(hash);
|
|
797
|
+
if (subscribers) {
|
|
798
|
+
for (const cb of subscribers) cb(queryState.records);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** True while ≥1 live subscriber is watching this query (refcount guard). */
|
|
803
|
+
hasSubscribers(hash: string): boolean {
|
|
804
|
+
return (this.subscriptions.get(hash)?.size ?? 0) > 0;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Opt-in eager teardown for a query whose LAST subscriber just left — used by
|
|
809
|
+
* viewport-windowed lists to cancel off-screen windows instead of leaving
|
|
810
|
+
* their remote views to expire on the TTL sweep. No-op while any subscriber
|
|
811
|
+
* remains (refcount). Only enqueues the remote cleanup here; the local WASM
|
|
812
|
+
* view + in-memory state are freed in {@link finalizeDeregister} after the
|
|
813
|
+
* remote delete completes, so a re-subscribe in between aborts/heals it.
|
|
814
|
+
*
|
|
815
|
+
* NOTE: most queries should NOT use this — the default keep-alive on
|
|
816
|
+
* unsubscribe avoids re-registration churn on navigation.
|
|
817
|
+
*/
|
|
818
|
+
deregisterQuery(hash: string): void {
|
|
819
|
+
if (this.hasSubscribers(hash)) return;
|
|
820
|
+
if (!this.activeQueries.has(hash)) return;
|
|
821
|
+
this.onDeregister?.(hash);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Final local teardown after the remote `_00_query` row was deleted: free the
|
|
826
|
+
* WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
|
|
827
|
+
* (`cleanupQuery`) guarantees no subscriber remains.
|
|
828
|
+
*/
|
|
829
|
+
finalizeDeregister(hash: string): void {
|
|
830
|
+
const qs = this.activeQueries.get(hash);
|
|
831
|
+
if (qs?.ttlTimer) {
|
|
832
|
+
clearTimeout(qs.ttlTimer);
|
|
833
|
+
qs.ttlTimer = null;
|
|
834
|
+
}
|
|
835
|
+
const debounce = this.debounceTimers.get(hash);
|
|
836
|
+
if (debounce) {
|
|
837
|
+
clearTimeout(debounce);
|
|
838
|
+
this.debounceTimers.delete(hash);
|
|
839
|
+
}
|
|
840
|
+
this.pendingStreamUpdates.delete(hash);
|
|
841
|
+
this.fetchDepth.delete(hash);
|
|
842
|
+
this.cache.unregisterQuery(hash);
|
|
843
|
+
this.activeQueries.delete(hash);
|
|
844
|
+
this.subscriptions.delete(hash);
|
|
845
|
+
}
|
|
846
|
+
|
|
263
847
|
/**
|
|
264
848
|
* Get query state by id (for sync and devtools)
|
|
265
849
|
*/
|
|
@@ -274,36 +858,163 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
274
858
|
return Array.from(this.activeQueries.values());
|
|
275
859
|
}
|
|
276
860
|
|
|
861
|
+
getActiveQueryHashes(): QueryHash[] {
|
|
862
|
+
return Array.from(this.activeQueries.keys());
|
|
863
|
+
}
|
|
864
|
+
|
|
277
865
|
async updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void> {
|
|
278
866
|
const queryState = this.activeQueries.get(id);
|
|
279
867
|
if (!queryState) {
|
|
280
868
|
this.logger.warn(
|
|
281
|
-
{ id, Category: '
|
|
869
|
+
{ id, Category: 'sp00ky-client::DataModule::updateQueryLocalArray' },
|
|
282
870
|
'Query to update local array not found'
|
|
283
871
|
);
|
|
284
872
|
return;
|
|
285
873
|
}
|
|
874
|
+
const epoch = this.local.epoch;
|
|
286
875
|
queryState.config.localArray = localArray;
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
876
|
+
try {
|
|
877
|
+
await this.local.query(
|
|
878
|
+
surql.seal(surql.updateSet('id', ['localArray'])),
|
|
879
|
+
{
|
|
880
|
+
id: queryState.config.id,
|
|
881
|
+
localArray,
|
|
882
|
+
},
|
|
883
|
+
{ epoch }
|
|
884
|
+
);
|
|
885
|
+
} catch (err) {
|
|
886
|
+
if (err instanceof StaleEpochError) return;
|
|
887
|
+
throw err;
|
|
888
|
+
}
|
|
291
889
|
}
|
|
292
890
|
|
|
293
891
|
async updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void> {
|
|
294
892
|
const queryState = this.getQueryByHash(hash);
|
|
295
893
|
if (!queryState) {
|
|
296
894
|
this.logger.warn(
|
|
297
|
-
{ hash, Category: '
|
|
895
|
+
{ hash, Category: 'sp00ky-client::DataModule::updateQueryRemoteArray' },
|
|
298
896
|
'Query to update remote array not found'
|
|
299
897
|
);
|
|
300
898
|
return;
|
|
301
899
|
}
|
|
900
|
+
const epoch = this.local.epoch;
|
|
302
901
|
queryState.config.remoteArray = remoteArray;
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
902
|
+
try {
|
|
903
|
+
await this.local.query(
|
|
904
|
+
surql.seal(surql.updateSet('id', ['remoteArray'])),
|
|
905
|
+
{
|
|
906
|
+
id: queryState.config.id,
|
|
907
|
+
remoteArray,
|
|
908
|
+
},
|
|
909
|
+
{ epoch }
|
|
910
|
+
);
|
|
911
|
+
} catch (err) {
|
|
912
|
+
if (err instanceof StaleEpochError) return;
|
|
913
|
+
throw err;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* Cancel every armed timer ahead of a local-bucket switch: stream-update
|
|
919
|
+
* debounce timers (their pending updates carry the OLD bucket's id-sets) and
|
|
920
|
+
* per-query TTL heartbeats (they'd refresh the previous user's remote
|
|
921
|
+
* `_00_query` rows under the new session). The rebind re-arms heartbeats.
|
|
922
|
+
*/
|
|
923
|
+
quiesce(): void {
|
|
924
|
+
for (const timer of this.debounceTimers.values()) {
|
|
925
|
+
clearTimeout(timer);
|
|
926
|
+
}
|
|
927
|
+
this.debounceTimers.clear();
|
|
928
|
+
this.pendingStreamUpdates.clear();
|
|
929
|
+
this.fetchDepth.clear();
|
|
930
|
+
for (const queryState of this.activeQueries.values()) {
|
|
931
|
+
if (queryState.ttlTimer) {
|
|
932
|
+
clearTimeout(queryState.ttlTimer);
|
|
933
|
+
queryState.ttlTimer = null;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Re-home every active query in a freshly-opened bucket, KEEPING its hash —
|
|
940
|
+
* `useQuery` subscriptions are keyed by hash and don't re-register on auth
|
|
941
|
+
* changes, so the hooks must stay attached. Per query:
|
|
942
|
+
* 1. reset the sync arrays + hydration flag and drop the previous user's
|
|
943
|
+
* records, notifying subscribers with the new-bucket materialization
|
|
944
|
+
* (usually empty) so their rows leave the UI immediately;
|
|
945
|
+
* 2. recreate the `_00_query` row in the new bucket;
|
|
946
|
+
* 3. re-register the SSP view on the (fresh, post-reset) processor — this
|
|
947
|
+
* also rebinds the view to the NEW `$auth` context;
|
|
948
|
+
* 4. restart the TTL heartbeat.
|
|
949
|
+
* Returns the hashes so the caller can enqueue remote re-registration, which
|
|
950
|
+
* refills records from the server via the normal register→sync→notify path.
|
|
951
|
+
*/
|
|
952
|
+
async rebindAfterBucketSwitch(): Promise<QueryHash[]> {
|
|
953
|
+
const hashes: QueryHash[] = [];
|
|
954
|
+
for (const [hash, queryState] of this.activeQueries.entries()) {
|
|
955
|
+
const config = queryState.config;
|
|
956
|
+
config.localArray = [];
|
|
957
|
+
config.remoteArray = [];
|
|
958
|
+
config.subqueryRemoteArray = undefined;
|
|
959
|
+
queryState.hydrated = false;
|
|
960
|
+
queryState.syncNotified = false;
|
|
961
|
+
queryState.records = [];
|
|
962
|
+
// Via setQueryStatus (not a bare assignment) so status observers see the
|
|
963
|
+
// flip back to a loading state.
|
|
964
|
+
this.setQueryStatus(hash, 'fetching');
|
|
965
|
+
|
|
966
|
+
try {
|
|
967
|
+
await withRetry(this.logger, () =>
|
|
968
|
+
this.local.query<[QueryConfigRecord]>(surql.seal(surql.create('id', 'data')), {
|
|
969
|
+
id: config.id,
|
|
970
|
+
data: {
|
|
971
|
+
surql: config.surql,
|
|
972
|
+
params: config.params,
|
|
973
|
+
localArray: [],
|
|
974
|
+
remoteArray: [],
|
|
975
|
+
lastActiveAt: new Date(),
|
|
976
|
+
createdAt: new Date(),
|
|
977
|
+
ttl: config.ttl,
|
|
978
|
+
tableName: config.tableName,
|
|
979
|
+
updateCount: queryState.updateCount,
|
|
980
|
+
rowCount: 0,
|
|
981
|
+
errorCount: queryState.errorCount,
|
|
982
|
+
},
|
|
983
|
+
})
|
|
984
|
+
);
|
|
985
|
+
|
|
986
|
+
const { localArray } = this.cache.registerQuery({
|
|
987
|
+
queryHash: hash,
|
|
988
|
+
surql: config.surql,
|
|
989
|
+
params: config.params,
|
|
990
|
+
ttl: new Duration(config.ttl),
|
|
991
|
+
lastActiveAt: new Date(),
|
|
992
|
+
});
|
|
993
|
+
config.localArray = localArray;
|
|
994
|
+
await this.local.query(surql.seal(surql.updateSet('id', ['localArray', 'rowCount'])), {
|
|
995
|
+
id: config.id,
|
|
996
|
+
localArray,
|
|
997
|
+
rowCount: localArray.length,
|
|
998
|
+
});
|
|
999
|
+
} catch (err) {
|
|
1000
|
+
this.logger.error(
|
|
1001
|
+
{ err, hash, Category: 'sp00ky-client::DataModule::rebindAfterBucketSwitch' },
|
|
1002
|
+
'Failed to rebind query after bucket switch; remote re-registration will retry'
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
// Notify AFTER the SSP re-registration so a subscriber that re-reads
|
|
1007
|
+
// synchronously sees consistent (empty) state.
|
|
1008
|
+
const subscribers = this.subscriptions.get(hash);
|
|
1009
|
+
if (subscribers) {
|
|
1010
|
+
for (const callback of subscribers) {
|
|
1011
|
+
callback(queryState.records);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
this.startTTLHeartbeat(queryState, hash);
|
|
1015
|
+
hashes.push(hash);
|
|
1016
|
+
}
|
|
1017
|
+
return hashes;
|
|
307
1018
|
}
|
|
308
1019
|
|
|
309
1020
|
/**
|
|
@@ -313,20 +1024,29 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
313
1024
|
async notifyQuerySynced(queryHash: string): Promise<void> {
|
|
314
1025
|
const queryState = this.activeQueries.get(queryHash);
|
|
315
1026
|
if (!queryState) return;
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
);
|
|
322
|
-
|
|
1027
|
+
const epoch = this.local.epoch;
|
|
1028
|
+
|
|
1029
|
+
// Re-query local DB for latest data (windowed queries materialize from the
|
|
1030
|
+
// list_ref window so they resolve even if the in-browser SSP never emits —
|
|
1031
|
+
// it can't compute a high offset whose preceding rows aren't resident).
|
|
1032
|
+
const newRecords = await this.materializeRecords(queryState);
|
|
1033
|
+
// Bucket switched while we materialized: these rows mix old-bucket reads
|
|
1034
|
+
// with new-bucket state — drop them; the rebind/re-registration re-emits.
|
|
1035
|
+
if (epoch !== this.local.epoch) return;
|
|
323
1036
|
const changed = JSON.stringify(queryState.records) !== JSON.stringify(newRecords);
|
|
324
1037
|
queryState.records = newRecords;
|
|
325
1038
|
|
|
326
|
-
// Notify if data changed OR if this
|
|
327
|
-
// The latter handles "query truly has no
|
|
328
|
-
|
|
1039
|
+
// Notify if data changed OR if this registration lifetime hasn't emitted a
|
|
1040
|
+
// post-sync notification yet. The latter handles "query truly has no
|
|
1041
|
+
// results" so the UI can stop loading — gated on the in-memory
|
|
1042
|
+
// `syncNotified` flag rather than `updateCount === 0`, because updateCount
|
|
1043
|
+
// is PERSISTED across deregister/re-register: a re-registered empty window
|
|
1044
|
+
// (updateCount > 0, records unchanged) would otherwise never emit and its
|
|
1045
|
+
// subscribers would show a loading state forever.
|
|
1046
|
+
if (changed || !queryState.syncNotified) {
|
|
1047
|
+
queryState.syncNotified = true;
|
|
329
1048
|
queryState.updateCount++;
|
|
1049
|
+
queryState.lastUpdatedAt = Date.now();
|
|
330
1050
|
const subscribers = this.subscriptions.get(queryHash);
|
|
331
1051
|
if (subscribers) {
|
|
332
1052
|
for (const callback of subscribers) {
|
|
@@ -370,6 +1090,14 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
370
1090
|
retry_strategy: options?.retry_strategy ?? 'linear',
|
|
371
1091
|
};
|
|
372
1092
|
|
|
1093
|
+
if (options?.timeout != null) {
|
|
1094
|
+
record.timeout = options.timeout;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (options?.delay != null) {
|
|
1098
|
+
record.delay = options.delay;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
373
1101
|
if (options?.assignedTo) {
|
|
374
1102
|
record.assigned_to = options.assignedTo;
|
|
375
1103
|
}
|
|
@@ -392,7 +1120,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
392
1120
|
|
|
393
1121
|
const rid = parseRecordIdString(id);
|
|
394
1122
|
const params = parseParams(tableSchema.columns, data);
|
|
395
|
-
const mutationId = parseRecordIdString(`
|
|
1123
|
+
const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
|
|
396
1124
|
|
|
397
1125
|
const dataKeys = Object.keys(params).map((key) => ({ key, variable: `data_${key}` }));
|
|
398
1126
|
const prefixedParams = Object.fromEntries(
|
|
@@ -441,7 +1169,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
441
1169
|
callback([mutationEvent]);
|
|
442
1170
|
}
|
|
443
1171
|
|
|
444
|
-
this.logger.debug({ id, Category: '
|
|
1172
|
+
this.logger.debug({ id, Category: 'sp00ky-client::DataModule::create' }, 'Record created');
|
|
445
1173
|
|
|
446
1174
|
return target;
|
|
447
1175
|
}
|
|
@@ -463,7 +1191,10 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
463
1191
|
|
|
464
1192
|
const rid = parseRecordIdString(id);
|
|
465
1193
|
const params = parseParams(tableSchema.columns, data);
|
|
466
|
-
const mutationId = parseRecordIdString(`
|
|
1194
|
+
const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
|
|
1195
|
+
|
|
1196
|
+
// Note: CRDT state is pushed directly to the _00_crdt table by CrdtField.pushToRemote(),
|
|
1197
|
+
// NOT through the record update pipeline. This keeps the record data clean.
|
|
467
1198
|
|
|
468
1199
|
// Capture current record state before mutation for rollback support
|
|
469
1200
|
const [beforeRecord] = await withRetry(this.logger, () =>
|
|
@@ -472,7 +1203,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
472
1203
|
|
|
473
1204
|
const query = surql.seal<{ target: T }>(
|
|
474
1205
|
surql.tx([
|
|
475
|
-
surql.updateSet('id', [{ statement: '
|
|
1206
|
+
surql.updateSet('id', [{ statement: '_00_rv += 1' }]),
|
|
476
1207
|
surql.let('updated', surql.updateMerge('id', 'data')),
|
|
477
1208
|
surql.createMutation('update', 'mid', 'id', 'data'),
|
|
478
1209
|
surql.returnObject([{ key: 'target', variable: 'updated' }]),
|
|
@@ -496,8 +1227,8 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
496
1227
|
updatedFields[key] = (target as Record<string, any>)[key];
|
|
497
1228
|
}
|
|
498
1229
|
}
|
|
499
|
-
if ('
|
|
500
|
-
updatedFields.
|
|
1230
|
+
if ('_00_rv' in (target as Record<string, any>)) {
|
|
1231
|
+
updatedFields._00_rv = (target as Record<string, any>)._00_rv;
|
|
501
1232
|
}
|
|
502
1233
|
this.replaceRecordInQueries(updatedFields);
|
|
503
1234
|
|
|
@@ -509,7 +1240,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
509
1240
|
table: table,
|
|
510
1241
|
op: 'UPDATE',
|
|
511
1242
|
record: parsedRecord,
|
|
512
|
-
version: target.
|
|
1243
|
+
version: target._00_rv as number,
|
|
513
1244
|
},
|
|
514
1245
|
true
|
|
515
1246
|
);
|
|
@@ -531,7 +1262,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
531
1262
|
callback([mutationEvent]);
|
|
532
1263
|
}
|
|
533
1264
|
|
|
534
|
-
this.logger.debug({ id, Category: '
|
|
1265
|
+
this.logger.debug({ id, Category: 'sp00ky-client::DataModule::update' }, 'Record updated');
|
|
535
1266
|
|
|
536
1267
|
return target;
|
|
537
1268
|
}
|
|
@@ -547,14 +1278,53 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
547
1278
|
}
|
|
548
1279
|
|
|
549
1280
|
const rid = parseRecordIdString(id);
|
|
550
|
-
const mutationId = parseRecordIdString(`
|
|
1281
|
+
const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
|
|
1282
|
+
|
|
1283
|
+
// Fetch the record before deleting so DBSP can match it against query predicates
|
|
1284
|
+
const [beforeRecords] = await this.local.query<[Record<string, any>[]]>(
|
|
1285
|
+
'SELECT * FROM ONLY $id',
|
|
1286
|
+
{ id: rid }
|
|
1287
|
+
);
|
|
1288
|
+
const beforeRecord = beforeRecords ?? {};
|
|
551
1289
|
|
|
552
1290
|
const query = surql.seal<void>(
|
|
553
1291
|
surql.tx([surql.delete('id'), surql.createMutation('delete', 'mid', 'id')])
|
|
554
1292
|
);
|
|
555
1293
|
|
|
556
1294
|
await withRetry(this.logger, () => this.local.execute(query, { id: rid, mid: mutationId }));
|
|
557
|
-
|
|
1295
|
+
|
|
1296
|
+
// The local DELETE has now committed. Everything below must reflect that in
|
|
1297
|
+
// active live queries — so the deleted row disappears optimistically without
|
|
1298
|
+
// a reload — even if the optimistic SSP-view ingest below fails. Previously a
|
|
1299
|
+
// throw from `cache.delete` (the WASM ingest) aborted `delete()` after the
|
|
1300
|
+
// commit, so the manual notify loop never ran and the row lingered on screen
|
|
1301
|
+
// until reload. Ingesting the delete into the in-browser SSP view is
|
|
1302
|
+
// best-effort: the manual re-materialize reads the local DB (which already
|
|
1303
|
+
// excludes the row), so the result is correct regardless.
|
|
1304
|
+
try {
|
|
1305
|
+
await this.cache.delete(table, id, true, beforeRecord);
|
|
1306
|
+
} catch (err) {
|
|
1307
|
+
this.logger.error(
|
|
1308
|
+
{ err, id, Category: 'sp00ky-client::DataModule::delete' },
|
|
1309
|
+
'SSP delete-ingest failed; relying on query re-materialize to reflect the delete'
|
|
1310
|
+
);
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// DBSP may not emit view updates for DELETE ops — manually notify all queries
|
|
1314
|
+
// that reference this table. Each is isolated so one failing re-materialize
|
|
1315
|
+
// can't stop the others (or the sync emit below) from running.
|
|
1316
|
+
for (const [queryHash, queryState] of this.activeQueries) {
|
|
1317
|
+
if (queryState.config.tableName === tableName) {
|
|
1318
|
+
try {
|
|
1319
|
+
await this.notifyQuerySynced(queryHash);
|
|
1320
|
+
} catch (err) {
|
|
1321
|
+
this.logger.error(
|
|
1322
|
+
{ err, queryHash, Category: 'sp00ky-client::DataModule::delete' },
|
|
1323
|
+
'notifyQuerySynced failed after delete'
|
|
1324
|
+
);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
558
1328
|
|
|
559
1329
|
// Emit mutation event
|
|
560
1330
|
const mutationEvent: DeleteEvent = {
|
|
@@ -567,7 +1337,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
567
1337
|
callback([mutationEvent]);
|
|
568
1338
|
}
|
|
569
1339
|
|
|
570
|
-
this.logger.debug({ id, Category: '
|
|
1340
|
+
this.logger.debug({ id, Category: 'sp00ky-client::DataModule::delete' }, 'Record deleted');
|
|
571
1341
|
}
|
|
572
1342
|
|
|
573
1343
|
// ==================== ROLLBACK METHODS ====================
|
|
@@ -586,12 +1356,12 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
586
1356
|
this.removeRecordFromQueries(recordId);
|
|
587
1357
|
|
|
588
1358
|
this.logger.info(
|
|
589
|
-
{ id, tableName, Category: '
|
|
1359
|
+
{ id, tableName, Category: 'sp00ky-client::DataModule::rollbackCreate' },
|
|
590
1360
|
'Rolled back optimistic create'
|
|
591
1361
|
);
|
|
592
1362
|
} catch (err) {
|
|
593
1363
|
this.logger.error(
|
|
594
|
-
{ err, id, tableName, Category: '
|
|
1364
|
+
{ err, id, tableName, Category: 'sp00ky-client::DataModule::rollbackCreate' },
|
|
595
1365
|
'Failed to rollback create'
|
|
596
1366
|
);
|
|
597
1367
|
}
|
|
@@ -626,7 +1396,7 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
626
1396
|
table: tableName,
|
|
627
1397
|
op: 'UPDATE',
|
|
628
1398
|
record: parsedRecord,
|
|
629
|
-
version: (beforeRecord.
|
|
1399
|
+
version: (beforeRecord._00_rv as number) || 1,
|
|
630
1400
|
},
|
|
631
1401
|
true
|
|
632
1402
|
);
|
|
@@ -635,12 +1405,12 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
635
1405
|
await this.replaceRecordInQueries(beforeRecord);
|
|
636
1406
|
|
|
637
1407
|
this.logger.info(
|
|
638
|
-
{ id, tableName, Category: '
|
|
1408
|
+
{ id, tableName, Category: 'sp00ky-client::DataModule::rollbackUpdate' },
|
|
639
1409
|
'Rolled back optimistic update'
|
|
640
1410
|
);
|
|
641
1411
|
} catch (err) {
|
|
642
1412
|
this.logger.error(
|
|
643
|
-
{ err, id, tableName, Category: '
|
|
1413
|
+
{ err, id, tableName, Category: 'sp00ky-client::DataModule::rollbackUpdate' },
|
|
644
1414
|
'Failed to rollback update'
|
|
645
1415
|
);
|
|
646
1416
|
}
|
|
@@ -678,7 +1448,8 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
678
1448
|
surqlString: string,
|
|
679
1449
|
params: Record<string, any>,
|
|
680
1450
|
ttl: QueryTimeToLive,
|
|
681
|
-
tableName: T
|
|
1451
|
+
tableName: T,
|
|
1452
|
+
plan?: QueryPlan
|
|
682
1453
|
): Promise<QueryHash> {
|
|
683
1454
|
const queryState = await this.createNewQuery<T>({
|
|
684
1455
|
recordId,
|
|
@@ -686,31 +1457,76 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
686
1457
|
params,
|
|
687
1458
|
ttl,
|
|
688
1459
|
tableName,
|
|
1460
|
+
plan,
|
|
689
1461
|
});
|
|
690
1462
|
|
|
691
|
-
const
|
|
1463
|
+
const t0 = performance.now();
|
|
1464
|
+
const { localArray, registrationTimings } = this.cache.registerQuery({
|
|
692
1465
|
queryHash: hash,
|
|
693
1466
|
surql: surqlString,
|
|
694
1467
|
params,
|
|
695
1468
|
ttl: new Duration(ttl),
|
|
696
1469
|
lastActiveAt: new Date(),
|
|
697
1470
|
});
|
|
1471
|
+
const registrationTime = performance.now() - t0;
|
|
1472
|
+
|
|
1473
|
+
// Record the one-shot SSP registration timings (parse/plan/snapshot from the
|
|
1474
|
+
// WASM binding) + the register_view wall time for DevTools.
|
|
1475
|
+
queryState.registrationTimings = {
|
|
1476
|
+
parseMs: registrationTimings?.parseMs ?? null,
|
|
1477
|
+
planMs: registrationTimings?.planMs ?? null,
|
|
1478
|
+
snapshotMs: registrationTimings?.snapshotMs ?? null,
|
|
1479
|
+
wallMs: registrationTime,
|
|
1480
|
+
};
|
|
698
1481
|
|
|
699
1482
|
await withRetry(this.logger, () =>
|
|
700
|
-
this.local.query(
|
|
701
|
-
id
|
|
702
|
-
|
|
703
|
-
|
|
1483
|
+
this.local.query(
|
|
1484
|
+
surql.seal(surql.updateSet('id', ['localArray', 'registrationTime', 'rowCount'])),
|
|
1485
|
+
{
|
|
1486
|
+
id: recordId,
|
|
1487
|
+
localArray,
|
|
1488
|
+
registrationTime,
|
|
1489
|
+
rowCount: localArray.length,
|
|
1490
|
+
}
|
|
1491
|
+
)
|
|
704
1492
|
);
|
|
705
1493
|
|
|
1494
|
+
// Windowed (`START n`) queries skipped the raw initial load in
|
|
1495
|
+
// createNewQuery (O(offset) + wrong rows for sparse windows). Seed the
|
|
1496
|
+
// initial rows now from the SSP's window id-set (`localArray`) via the same
|
|
1497
|
+
// window-materialization path the stream updates use — O(window), and the
|
|
1498
|
+
// ids are already the correct window — so the first paint isn't empty while
|
|
1499
|
+
// the remote `_00_list_ref` syncs in.
|
|
1500
|
+
const windowMat = buildWindowMaterialization(surqlString);
|
|
1501
|
+
if (windowMat && localArray.length > 0) {
|
|
1502
|
+
try {
|
|
1503
|
+
const winIds = localArray.map(([id]) => parseRecordIdString(id));
|
|
1504
|
+
if (plan) {
|
|
1505
|
+
const winPlan = buildWindowMaterializationPlan(plan, winIds) ?? { ...plan, ids: winIds };
|
|
1506
|
+
queryState.records = await this.local.select(winPlan, params);
|
|
1507
|
+
} else {
|
|
1508
|
+
const [seeded] = await this.local.query<[Record<string, any>[]]>(windowMat.query, {
|
|
1509
|
+
...params,
|
|
1510
|
+
__win: winIds,
|
|
1511
|
+
});
|
|
1512
|
+
queryState.records = seeded || [];
|
|
1513
|
+
}
|
|
1514
|
+
} catch (err) {
|
|
1515
|
+
this.logger.warn(
|
|
1516
|
+
{ err, hash, Category: 'sp00ky-client::DataModule::createAndRegisterQuery' },
|
|
1517
|
+
'Failed to seed windowed initial records from localArray'
|
|
1518
|
+
);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
|
|
706
1522
|
this.activeQueries.set(hash, queryState);
|
|
707
|
-
this.startTTLHeartbeat(queryState);
|
|
1523
|
+
this.startTTLHeartbeat(queryState, hash);
|
|
708
1524
|
this.logger.debug(
|
|
709
1525
|
{
|
|
710
1526
|
hash,
|
|
711
1527
|
tableName,
|
|
712
1528
|
recordCount: queryState.records.length,
|
|
713
|
-
Category: '
|
|
1529
|
+
Category: 'sp00ky-client::DataModule::query',
|
|
714
1530
|
},
|
|
715
1531
|
'Query registered'
|
|
716
1532
|
);
|
|
@@ -724,12 +1540,14 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
724
1540
|
params,
|
|
725
1541
|
ttl,
|
|
726
1542
|
tableName,
|
|
1543
|
+
plan,
|
|
727
1544
|
}: {
|
|
728
1545
|
recordId: RecordId;
|
|
729
1546
|
surql: string;
|
|
730
1547
|
params: Record<string, any>;
|
|
731
1548
|
ttl: QueryTimeToLive;
|
|
732
1549
|
tableName: T;
|
|
1550
|
+
plan?: QueryPlan;
|
|
733
1551
|
}): Promise<QueryState> {
|
|
734
1552
|
const tableSchema = this.schema.tables.find((t) => t.name === tableName);
|
|
735
1553
|
if (!tableSchema) {
|
|
@@ -752,8 +1570,12 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
752
1570
|
localArray: [],
|
|
753
1571
|
remoteArray: [],
|
|
754
1572
|
lastActiveAt: new Date(),
|
|
1573
|
+
createdAt: new Date(),
|
|
755
1574
|
ttl,
|
|
756
1575
|
tableName,
|
|
1576
|
+
updateCount: 0,
|
|
1577
|
+
rowCount: 0,
|
|
1578
|
+
errorCount: 0,
|
|
757
1579
|
},
|
|
758
1580
|
})
|
|
759
1581
|
);
|
|
@@ -763,62 +1585,111 @@ export class DataModule<S extends SchemaStructure> {
|
|
|
763
1585
|
const config: QueryConfig = {
|
|
764
1586
|
...configRecord,
|
|
765
1587
|
id: recordId,
|
|
1588
|
+
// In-memory only — carries the engine-neutral plan so non-SurrealQL local
|
|
1589
|
+
// engines materialize via `select(plan)` instead of parsing `surql`.
|
|
1590
|
+
plan,
|
|
766
1591
|
params: parseParams(tableSchema.columns, configRecord.params),
|
|
767
1592
|
};
|
|
768
1593
|
|
|
769
1594
|
let records: Record<string, any>[] = [];
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
1595
|
+
// Windowed (`START n`) queries: do NOT seed from the raw surql here. Running
|
|
1596
|
+
// `… LIMIT n START m` against the shared local store is O(m) — it sorts and
|
|
1597
|
+
// skips m rows on every window open — AND returns the wrong rows for sparse
|
|
1598
|
+
// windows (the reason `buildWindowMaterialization` exists). Those windows are
|
|
1599
|
+
// seeded from the SSP `localArray` in `createAndRegisterQuery` instead.
|
|
1600
|
+
if (buildWindowMaterialization(surqlString) === null) {
|
|
1601
|
+
try {
|
|
1602
|
+
// Prefer the engine-neutral plan (required for non-SurrealQL engines);
|
|
1603
|
+
// fall back to running the raw surql on the SurrealDB engine.
|
|
1604
|
+
const result = plan
|
|
1605
|
+
? await this.local.select(plan, params)
|
|
1606
|
+
: (await this.local.query<[Record<string, any>[]]>(surqlString, params))[0];
|
|
1607
|
+
records = result || [];
|
|
1608
|
+
} catch (err) {
|
|
1609
|
+
this.logger.warn(
|
|
1610
|
+
{ err, Category: 'sp00ky-client::DataModule::createNewQuery' },
|
|
1611
|
+
'Failed to load initial cached records'
|
|
1612
|
+
);
|
|
1613
|
+
}
|
|
778
1614
|
}
|
|
779
1615
|
|
|
1616
|
+
// Persisted counters survive a restart even though the rolling
|
|
1617
|
+
// sample window is rebuilt from scratch in memory.
|
|
1618
|
+
const persistedUpdateCount =
|
|
1619
|
+
typeof (configRecord as any)?.updateCount === 'number'
|
|
1620
|
+
? (configRecord as any).updateCount
|
|
1621
|
+
: 0;
|
|
1622
|
+
const persistedErrorCount =
|
|
1623
|
+
typeof (configRecord as any)?.errorCount === 'number'
|
|
1624
|
+
? (configRecord as any).errorCount
|
|
1625
|
+
: 0;
|
|
1626
|
+
|
|
780
1627
|
return {
|
|
781
1628
|
config,
|
|
782
1629
|
records,
|
|
783
1630
|
ttlTimer: null,
|
|
784
1631
|
ttlDurationMs: parseDuration(ttl),
|
|
785
|
-
updateCount:
|
|
1632
|
+
updateCount: persistedUpdateCount,
|
|
1633
|
+
lastUpdatedAt: null,
|
|
1634
|
+
materializationSamples: [],
|
|
1635
|
+
lastIngestLatencyMs: null,
|
|
1636
|
+
errorCount: persistedErrorCount,
|
|
1637
|
+
// Born `fetching`, not `idle`: every cold registration is followed by a
|
|
1638
|
+
// `register` down-event whose lifecycle (Sp00kySync.registerQuery) resolves
|
|
1639
|
+
// the status to `idle` once the initial sync completed. Starting idle left
|
|
1640
|
+
// a gap where a fresh windowed query looked settled while still empty.
|
|
1641
|
+
status: 'fetching',
|
|
1642
|
+
phaseSamples: {},
|
|
1643
|
+
phaseLast: {},
|
|
1644
|
+
registrationTimings: { parseMs: null, planMs: null, snapshotMs: null, wallMs: null },
|
|
786
1645
|
};
|
|
787
1646
|
}
|
|
788
1647
|
|
|
789
1648
|
private async calculateHash(data: any): Promise<string> {
|
|
790
|
-
|
|
1649
|
+
// sessionId is part of the hash so the same logical query from two
|
|
1650
|
+
// sessions (e.g. two browser tabs of the same user) lands on different
|
|
1651
|
+
// `_00_query` rows and doesn't fight over a shared one.
|
|
1652
|
+
const content = JSON.stringify({ ...data, sessionId: this.sessionId });
|
|
791
1653
|
const msgBuffer = new TextEncoder().encode(content);
|
|
792
1654
|
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
|
|
793
1655
|
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
794
1656
|
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
795
1657
|
}
|
|
796
1658
|
|
|
797
|
-
private startTTLHeartbeat(queryState: QueryState): void {
|
|
1659
|
+
private startTTLHeartbeat(queryState: QueryState, hash: QueryHash): void {
|
|
798
1660
|
if (queryState.ttlTimer) return;
|
|
799
1661
|
|
|
800
1662
|
const heartbeatTime = Math.floor(queryState.ttlDurationMs * 0.9);
|
|
801
1663
|
|
|
802
1664
|
queryState.ttlTimer = setTimeout(() => {
|
|
803
|
-
|
|
1665
|
+
queryState.ttlTimer = null;
|
|
1666
|
+
// Only keep the remote query alive while something is actually watching
|
|
1667
|
+
// it. With the server now sweeping ALL expired views (not just in-circuit
|
|
1668
|
+
// ones), an un-refreshed query WOULD be swept after its TTL — so a live
|
|
1669
|
+
// subscriber must heartbeat. An abandoned query (no subscribers) is left
|
|
1670
|
+
// to expire and get swept; its local view was already torn down at the
|
|
1671
|
+
// last unsubscribe, so we just stop the timer here.
|
|
1672
|
+
const subscriberCount = this.subscriptions.get(hash)?.size ?? 0;
|
|
1673
|
+
if (subscriberCount === 0) {
|
|
1674
|
+
this.logger.debug(
|
|
1675
|
+
{ hash, Category: 'sp00ky-client::DataModule::startTTLHeartbeat' },
|
|
1676
|
+
'TTL heartbeat: no subscribers, stopping'
|
|
1677
|
+
);
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
this.onHeartbeat?.(hash);
|
|
804
1681
|
this.logger.debug(
|
|
805
1682
|
{
|
|
1683
|
+
hash,
|
|
806
1684
|
id: encodeRecordId(queryState.config.id),
|
|
807
|
-
Category: '
|
|
1685
|
+
Category: 'sp00ky-client::DataModule::startTTLHeartbeat',
|
|
808
1686
|
},
|
|
809
|
-
'TTL heartbeat'
|
|
1687
|
+
'TTL heartbeat sent'
|
|
810
1688
|
);
|
|
811
|
-
this.startTTLHeartbeat(queryState);
|
|
1689
|
+
this.startTTLHeartbeat(queryState, hash);
|
|
812
1690
|
}, heartbeatTime);
|
|
813
1691
|
}
|
|
814
1692
|
|
|
815
|
-
private stopTTLHeartbeat(queryState: QueryState): void {
|
|
816
|
-
if (queryState.ttlTimer) {
|
|
817
|
-
clearTimeout(queryState.ttlTimer);
|
|
818
|
-
queryState.ttlTimer = null;
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
|
|
822
1693
|
private async replaceRecordInQueries(record: Record<string, any>): Promise<void> {
|
|
823
1694
|
for (const [queryHash, queryState] of this.activeQueries.entries()) {
|
|
824
1695
|
const index = queryState.records.findIndex((r) => r.id === record.id);
|
|
@@ -851,7 +1722,7 @@ export function parseUpdateOptions(
|
|
|
851
1722
|
const delay = options.debounced !== true ? (options.debounced?.delay ?? 200) : 200;
|
|
852
1723
|
const keyType = options.debounced !== true ? (options.debounced?.key ?? id) : id;
|
|
853
1724
|
const key =
|
|
854
|
-
keyType === 'recordId_x_fields' ? `${id}::${Object.keys(data).
|
|
1725
|
+
keyType === 'recordId_x_fields' ? `${id}::${Object.keys(data).toSorted().join('#')}` : id;
|
|
855
1726
|
|
|
856
1727
|
pushEventOptions = {
|
|
857
1728
|
debounced: {
|