@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10
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 +58 -21
- package/README.md +59 -16
- package/dist/index.d.ts +2235 -908
- package/dist/index.js +20424 -5052
- package/dist/live.d.ts +149 -0
- package/dist/live.js +739 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/pure.d.ts +401 -0
- package/dist/pure.js +24 -0
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +392 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +439 -0
- package/dist/sw.d.ts +207 -0
- package/dist/sw.js +393 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +477 -0
- package/dist/types.d.ts +2084 -82
- package/dist/worker-edges.js +498 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +48 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +39 -8
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +186 -0
- package/skills/sp00ky-core/SKILL.md +44 -8
- package/skills/sp00ky-core/references/config.md +8 -2
- package/src/boot/auth-flip.saga.test.ts +174 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +203 -0
- package/src/boot/boot.saga.ts +146 -0
- package/src/boot/bucket-switch.saga.test.ts +191 -0
- package/src/boot/bucket-switch.saga.ts +151 -0
- package/src/boot/preload.saga.test.ts +96 -0
- package/src/boot/preload.saga.ts +45 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/client/bucket-handle.test.ts +195 -0
- package/src/client/bucket-handle.ts +372 -0
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/router.test.ts +59 -0
- package/src/client/router.ts +104 -0
- package/src/client/runtime.test.ts +319 -0
- package/src/client/runtime.ts +307 -0
- package/src/client/services.test.ts +74 -0
- package/src/client/services.ts +440 -0
- package/src/client/sp00ky-client.test.ts +570 -0
- package/src/client/sp00ky-client.ts +875 -0
- package/src/index.ts +87 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +94 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +181 -0
- package/src/kernel/events.ts +60 -0
- package/src/kernel/interpreter.test.ts +133 -0
- package/src/kernel/interpreter.ts +151 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/live/index.test.ts +512 -0
- package/src/live/index.ts +1059 -0
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +209 -0
- package/src/modules/auth/auth.local-first.test.ts +228 -0
- package/src/modules/auth/auth.session-recheck.test.ts +140 -0
- package/src/modules/auth/events/index.ts +7 -1
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +209 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +516 -34
- package/src/modules/channel/channel.test.ts +752 -0
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +1497 -0
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +472 -0
- package/src/modules/crdt/acceptance.ts +75 -0
- package/src/modules/crdt/bytes.ts +50 -0
- package/src/modules/crdt/crdt-field.ts +82 -238
- package/src/modules/crdt/crdt.test.ts +546 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +740 -271
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/crdt/mirror.ts +37 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +661 -99
- package/src/modules/devtools/mutations.test.ts +92 -0
- package/src/modules/devtools/mutations.ts +160 -0
- package/src/modules/devtools/notify-throttle.test.ts +166 -0
- package/src/modules/devtools/state-shape.test.ts +263 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +169 -0
- package/src/modules/devtools/versions.ts +29 -0
- package/src/modules/feature-flag/index.test.ts +179 -1
- package/src/modules/feature-flag/index.ts +117 -10
- package/src/modules/ref-tables.test.ts +28 -1
- package/src/modules/ref-tables.ts +23 -1
- package/src/modules/web-push/index.test.ts +824 -0
- package/src/modules/web-push/index.ts +1027 -0
- package/src/mutation/ingest-outage.integration.test.ts +400 -0
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/mutation/mutation-id.test.ts +37 -0
- package/src/mutation/mutation-id.ts +35 -0
- package/src/mutation/pending-writes.integration.test.ts +175 -0
- package/src/mutation/push.saga.test.ts +361 -0
- package/src/mutation/push.saga.ts +245 -0
- package/src/mutation/rows.test.ts +278 -0
- package/src/mutation/rows.ts +515 -0
- package/src/mutation/tray.saga.test.ts +63 -0
- package/src/mutation/tray.saga.ts +48 -0
- package/src/mutation/write.saga.test.ts +436 -0
- package/src/mutation/write.saga.ts +384 -0
- package/src/pure.ts +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +531 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +65 -0
- package/src/query/fetch.saga.test.ts +199 -0
- package/src/query/fetch.saga.ts +120 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/query/id-set-plan.test.ts +132 -0
- package/src/query/lifecycle.saga.test.ts +274 -0
- package/src/query/lifecycle.saga.ts +186 -0
- package/src/query/list-ref-live.integration.test.ts +203 -0
- package/src/query/materialize.saga.test.ts +216 -0
- package/src/query/materialize.saga.ts +83 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +133 -0
- package/src/query/membership.saga.test.ts +514 -0
- package/src/query/membership.saga.ts +339 -0
- package/src/query/membership.test.ts +151 -0
- package/src/query/membership.ts +234 -0
- package/src/query/register.saga.test.ts +430 -0
- package/src/query/register.saga.ts +330 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/session-guard.integration.test.ts +304 -0
- package/src/query/sql.test.ts +118 -0
- package/src/query/sql.ts +174 -0
- package/src/{modules/data → query}/window-query.test.ts +22 -4
- package/src/{modules/data → query}/window-query.ts +86 -8
- package/src/services/blobs/blob-cache.test.ts +359 -0
- package/src/services/blobs/blob-cache.ts +603 -0
- package/src/services/blobs/blob-manifest.ts +227 -0
- package/src/services/blobs/blob-store.test.ts +77 -0
- package/src/services/blobs/blob-store.ts +359 -0
- package/src/services/blobs/blob.fixture.ts +90 -0
- package/src/services/blobs/index.ts +70 -0
- package/src/services/database/cache-engine.ts +223 -0
- package/src/services/database/connection-supervisor.test.ts +318 -0
- package/src/services/database/connection-supervisor.ts +422 -0
- package/src/services/database/database.query-timeout.test.ts +140 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +151 -56
- package/src/services/database/engine-factory.ts +40 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/index.ts +8 -0
- package/src/services/database/landed-body-clear.integration.test.ts +236 -0
- package/src/services/database/local-migrator.integration.test.ts +110 -0
- package/src/services/database/local-migrator.ts +54 -9
- package/src/services/database/local.test.ts +117 -0
- package/src/services/database/local.ts +364 -74
- package/src/services/database/plan-render.test.ts +159 -0
- package/src/services/database/plan-render.ts +108 -0
- package/src/services/database/relation-resolver.test.ts +484 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +283 -4
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +649 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1422 -0
- package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
- package/src/services/database/sqlite-column-reset.ts +91 -0
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
- package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
- package/src/services/database/sqlite-lock-verify.test.ts +33 -0
- package/src/services/database/sqlite-lock-verify.ts +45 -0
- package/src/services/database/sqlite-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +164 -0
- package/src/services/database/sqlite-plan-sql.ts +196 -0
- package/src/services/database/sqlite-projection.test.ts +121 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +261 -0
- package/src/services/database/sqlite-select.ts +131 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +231 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +417 -0
- package/src/services/database/surreal-cache-engine.ts +163 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +187 -6
- package/src/services/persistence/surrealdb.ts +2 -2
- package/src/services/stream-processor/index.ts +621 -93
- package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
- package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/wasm-types.ts +41 -1
- package/src/services/tabs/broker-client.ts +284 -0
- package/src/services/tabs/broker.test.ts +381 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +646 -0
- package/src/services/tabs/fake-ports.fixture.ts +112 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +262 -0
- package/src/services/tabs/support.ts +38 -0
- package/src/services/tabs/tabs-broker-worker.ts +652 -0
- package/src/sp00ky.ts +5 -648
- package/src/state/client-state.ts +231 -0
- package/src/state/lifecycle.test.ts +184 -0
- package/src/state/lifecycle.ts +127 -0
- package/src/state/reducers.test.ts +337 -0
- package/src/state/reducers.ts +571 -0
- package/src/state/selectors.test.ts +203 -0
- package/src/state/selectors.ts +264 -0
- package/src/sw/index.test.ts +582 -0
- package/src/sw/index.ts +607 -0
- package/src/sw/store.ts +96 -0
- package/src/sync/connection.saga.test.ts +97 -0
- package/src/sync/connection.saga.ts +89 -0
- package/src/sync/live.saga.test.ts +229 -0
- package/src/sync/live.saga.ts +116 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
- package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +78 -0
- package/src/sync/tabs.saga.ts +96 -0
- package/src/testing/adapters.ts +137 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +63 -0
- package/src/testing/run-pure.test.ts +92 -0
- package/src/testing/run-pure.ts +128 -0
- package/src/testing/services.ts +17 -0
- package/src/types.ts +601 -25
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +57 -0
- package/src/utils/error-classification.test.ts +116 -0
- package/src/utils/error-classification.ts +74 -0
- package/src/utils/index.ts +58 -3
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +62 -1
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/sha256.ts +15 -0
- package/src/utils/surql.ts +17 -15
- package/src/utils/utils.test.ts +3 -2
- package/tsdown.config.ts +105 -4
- package/vitest.config.ts +52 -0
- package/src/modules/cache/index.ts +0 -253
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/crdt/crdt-hydration.test.ts +0 -206
- package/src/modules/data/data.status.test.ts +0 -108
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -1491
- package/src/modules/sync/engine.ts +0 -227
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.ts +0 -90
- package/src/modules/sync/queue/queue-up.ts +0 -224
- package/src/modules/sync/scheduler.ts +0 -121
- package/src/modules/sync/sync.ts +0 -1244
- package/src/sp00ky.auth-order.test.ts +0 -65
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
import init, { Sp00kyProcessor } from '@spooky-sync/ssp-wasm';
|
|
3
3
|
import type { EventDefinition, EventSystem } from '../../events/index';
|
|
4
4
|
import type { Logger } from 'pino';
|
|
5
|
-
import type {
|
|
5
|
+
import type { LocalStore } from '../database/index';
|
|
6
6
|
import type { WasmProcessor, WasmStreamUpdate } from './wasm-types';
|
|
7
7
|
import type { Duration } from 'surrealdb';
|
|
8
|
-
import type {
|
|
8
|
+
import type { QueryTimeToLive, RecordVersionArray } from '../../types';
|
|
9
|
+
import { encodeRecordId } from '../../utils/index';
|
|
10
|
+
import { recordIdKey } from '../database/relation-resolver';
|
|
9
11
|
|
|
10
12
|
// Simple interface for query plan registration (replaces Incantation class)
|
|
11
13
|
interface QueryPlanConfig {
|
|
@@ -28,6 +30,14 @@ export interface StreamUpdate {
|
|
|
28
30
|
queryHash: string;
|
|
29
31
|
localArray: RecordVersionArray;
|
|
30
32
|
op?: 'CREATE' | 'UPDATE' | 'DELETE'; // Operation type for conditional debouncing
|
|
33
|
+
/**
|
|
34
|
+
* Client-internal: not from the circuit. A membership-only change that
|
|
35
|
+
* needed no fetch is re-materialized through this same path so it cannot
|
|
36
|
+
* race a real update (DataModule.scheduleRematerialize). Carries the last
|
|
37
|
+
* known `localArray`; consumers that describe an INGEST (persist, metrics,
|
|
38
|
+
* devtools events) skip it.
|
|
39
|
+
*/
|
|
40
|
+
synthetic?: boolean;
|
|
31
41
|
/**
|
|
32
42
|
* End-to-end ingest latency for the WASM call that produced this update,
|
|
33
43
|
* in milliseconds. Populated by StreamProcessorService.ingest. Undefined
|
|
@@ -57,6 +67,62 @@ export interface StreamUpdateReceiver {
|
|
|
57
67
|
onStreamUpdate(update: StreamUpdate): void;
|
|
58
68
|
}
|
|
59
69
|
|
|
70
|
+
/** One row change in the shape `ingestMany` consumes. */
|
|
71
|
+
export interface IngestRecord {
|
|
72
|
+
table: string;
|
|
73
|
+
/** `MERGE` overlays the given fields on the stored row (projection widening). */
|
|
74
|
+
op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
|
|
75
|
+
id: string;
|
|
76
|
+
record: any;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* What the boot-time prime needs from the client: which tables to walk, how
|
|
81
|
+
* to recognise a snapshot written under a different schema, and which rows'
|
|
82
|
+
* local `_00_rv` must not be reported as the server's.
|
|
83
|
+
*/
|
|
84
|
+
export interface CircuitPrimeContext {
|
|
85
|
+
tables: string[];
|
|
86
|
+
schemaHash: string;
|
|
87
|
+
/** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
|
|
88
|
+
* locally and may exceed the server's next version). */
|
|
89
|
+
pendingIds: Set<string>;
|
|
90
|
+
/** Each table's client column set (`columnFingerprints`). An engine that
|
|
91
|
+
* keeps bodies across schema changes resets the versions of a table whose
|
|
92
|
+
* set changed before they are read, so its rows are fetched again whole. */
|
|
93
|
+
columnFingerprints?: Record<string, string>;
|
|
94
|
+
/** Receives every `(id, rv)` the prime put into the circuit, per table, so
|
|
95
|
+
* the sync layer can skip re-downloading bodies it already has. */
|
|
96
|
+
onVersions?: (table: string, entries: [string, number][]) => void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Storage key of the circuit snapshot inside the local store. */
|
|
100
|
+
export const CIRCUIT_SNAPSHOT_KEY = 'circuit';
|
|
101
|
+
/** Bump when the bytes `load_store_state` reads change shape. */
|
|
102
|
+
export const CIRCUIT_SNAPSHOT_FORMAT = 1;
|
|
103
|
+
/** Rows per `ingest_many` call. Bounds the transient the wasm side allocates
|
|
104
|
+
* to parse a batch (measured: one 7700-row call of 20 KB bodies peaked at
|
|
105
|
+
* 500 MB, 128-row chunks at 335 MB, and under projection at 24 MB). */
|
|
106
|
+
const INGEST_CHUNK = 128;
|
|
107
|
+
/** Ids per `selectByIds` when priming bodies out of the local store. */
|
|
108
|
+
const PRIME_CHUNK = 256;
|
|
109
|
+
/** Rows the SurrealDB (main-thread, IndexedDB) engine is allowed to prime
|
|
110
|
+
* through; above this the circuit boots empty as it always did. */
|
|
111
|
+
const SURREAL_PRIME_ROW_CAP = 20_000;
|
|
112
|
+
/** Below this many changed rows the checkpoint timer stays quiet. */
|
|
113
|
+
const CHECKPOINT_MIN_ROWS = 50;
|
|
114
|
+
|
|
115
|
+
/** Stable `table:id` for a row id that may already be a string. */
|
|
116
|
+
function idString(id: unknown): string {
|
|
117
|
+
return typeof id === 'string' ? id : encodeRecordId(id as any);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function chunks<T>(items: T[], size: number): T[][] {
|
|
121
|
+
const out: T[][] = [];
|
|
122
|
+
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
60
126
|
export class StreamProcessorService {
|
|
61
127
|
private logger: Logger;
|
|
62
128
|
private processor: WasmProcessor | undefined;
|
|
@@ -75,11 +141,42 @@ export class StreamProcessorService {
|
|
|
75
141
|
// rejecting `$auth`-gated tables; the predicate just degrades to its public
|
|
76
142
|
// branch. Set via `setSessionAuth` on every auth state change.
|
|
77
143
|
private sessionAuth: { authId: string; access: string } = { authId: '', access: '' };
|
|
144
|
+
// Bumped by `reset()`. Anything captured before a reset (a checkpoint's
|
|
145
|
+
// bytes, a prime's chunk, a widening read) must not land on the NEW
|
|
146
|
+
// processor, which belongs to a different bucket.
|
|
147
|
+
private stateGeneration = 0;
|
|
148
|
+
// Shared-tabs: follower circuits are in-memory ONLY. Only the tab that owns
|
|
149
|
+
// the store writes its snapshot; a promoted follower flips this back on.
|
|
150
|
+
private persistState = true;
|
|
151
|
+
// Snapshot persistence. Store-only bytes, written by the checkpoint timer
|
|
152
|
+
// and on the page going hidden, never per ingest: `save_store_state` walks
|
|
153
|
+
// every row. The snapshot is what lets a reload restore the circuit and
|
|
154
|
+
// step in only what changed since (`reconcile`), instead of re-downloading
|
|
155
|
+
// and re-ingesting the whole working set.
|
|
156
|
+
private persistCircuit = false;
|
|
157
|
+
private checkpointMs = 30_000;
|
|
158
|
+
private checkpointTimer: ReturnType<typeof setInterval> | null = null;
|
|
159
|
+
private snapshotDirty = false;
|
|
160
|
+
private dirtyRows = 0;
|
|
161
|
+
private hideHandler: (() => void) | null = null;
|
|
162
|
+
private checkpointInFlight: Promise<void> | null = null;
|
|
163
|
+
// Keep only the fields registered plans evaluate per stored row. The client
|
|
164
|
+
// renders bodies from the local store, so a 20 KB game row in the circuit
|
|
165
|
+
// is ~150 B of predicate/sort fields under projection.
|
|
166
|
+
private projection = true;
|
|
167
|
+
// Prime state: `primed` resolves when the boot-time prime (snapshot restore
|
|
168
|
+
// + reconcile, or a full read of the local store) has finished, aborted or
|
|
169
|
+
// been skipped. Sync waits on it before its first diff.
|
|
170
|
+
private primed: Promise<void> = Promise.resolve();
|
|
171
|
+
private schemaHash: string | null = null;
|
|
172
|
+
// Projection widening, serialised: fields a new view evaluates that stored
|
|
173
|
+
// rows lack are merged in table by table.
|
|
174
|
+
private widenQueue: Promise<void> = Promise.resolve();
|
|
175
|
+
private widenPending: Map<string, Set<string>> = new Map();
|
|
78
176
|
|
|
79
177
|
constructor(
|
|
80
178
|
public events: EventSystem<StreamProcessorEvents>,
|
|
81
|
-
private db:
|
|
82
|
-
private persistenceClient: PersistenceClient,
|
|
179
|
+
private db: LocalStore,
|
|
83
180
|
logger: Logger
|
|
84
181
|
) {
|
|
85
182
|
this.logger = logger.child({ name: 'StreamProcessorService' });
|
|
@@ -128,35 +225,89 @@ export class StreamProcessorService {
|
|
|
128
225
|
}
|
|
129
226
|
|
|
130
227
|
/**
|
|
131
|
-
* Ingest a batch of record changes
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
228
|
+
* Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
|
|
229
|
+
* affected query once every record has been ingested. Use this whenever
|
|
230
|
+
* multiple records land at once (sync fetching N rows, the boot prime).
|
|
231
|
+
*
|
|
232
|
+
* The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
|
|
233
|
+
* circuit step per chunk (a step walks every registered view, so per-record
|
|
234
|
+
* ingest paid that fixed cost N times), but never the whole batch at once,
|
|
235
|
+
* because the wasm side has to hold every parsed row of a call at the same
|
|
236
|
+
* time and wasm32 dlmalloc never returns that peak.
|
|
137
237
|
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
238
|
+
* Returns the records that were ingested. A chunk that fails is reported
|
|
239
|
+
* and skipped, not retried (a retry would double-apply whatever the failed
|
|
240
|
+
* step already committed), and the remaining chunks still run.
|
|
141
241
|
*/
|
|
142
|
-
ingestMany(
|
|
143
|
-
records
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
242
|
+
ingestMany(records: IngestRecord[]): IngestRecord[] {
|
|
243
|
+
if (records.length === 0) return [];
|
|
244
|
+
|
|
245
|
+
if (!this.processor) {
|
|
246
|
+
this.logger.warn(
|
|
247
|
+
{ Category: 'sp00ky-client::StreamProcessorService::ingestMany' },
|
|
248
|
+
'Not initialized, skipping ingest'
|
|
249
|
+
);
|
|
250
|
+
return [];
|
|
251
|
+
}
|
|
151
252
|
|
|
253
|
+
const bulkIngest = this.processor.ingest_many;
|
|
254
|
+
if (typeof bulkIngest !== 'function') {
|
|
255
|
+
// Stale wasm build: per-record steps, still coalesced into one update.
|
|
256
|
+
this.beginCoalescing();
|
|
257
|
+
try {
|
|
258
|
+
for (const record of records) {
|
|
259
|
+
this.ingest(record.table, record.op, record.id, record.record);
|
|
260
|
+
}
|
|
261
|
+
} finally {
|
|
262
|
+
this.flushCoalescing();
|
|
263
|
+
}
|
|
264
|
+
return records;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const ingested: IngestRecord[] = [];
|
|
152
268
|
this.beginCoalescing();
|
|
153
269
|
try {
|
|
154
|
-
for (const
|
|
155
|
-
|
|
270
|
+
for (const chunk of chunks(records, INGEST_CHUNK)) {
|
|
271
|
+
try {
|
|
272
|
+
const items = chunk.map((record) => ({
|
|
273
|
+
table: record.table,
|
|
274
|
+
op: record.op,
|
|
275
|
+
id: record.id,
|
|
276
|
+
record: this.normalizeValue(record.record),
|
|
277
|
+
}));
|
|
278
|
+
const t0 = performance.now();
|
|
279
|
+
const rawUpdates = bulkIngest.call(this.processor, items) ?? [];
|
|
280
|
+
const materializationTimeMs = performance.now() - t0;
|
|
281
|
+
if (rawUpdates.length > 0) {
|
|
282
|
+
this.notifyUpdates(
|
|
283
|
+
rawUpdates.map((u: WasmStreamUpdate) => ({
|
|
284
|
+
queryHash: u.query_id,
|
|
285
|
+
localArray: u.result_data,
|
|
286
|
+
op: 'CREATE' as const,
|
|
287
|
+
materializationTimeMs,
|
|
288
|
+
storeApplyMs: u.timing_store_apply_ms,
|
|
289
|
+
circuitStepMs: u.timing_circuit_step_ms,
|
|
290
|
+
transformMs: u.timing_transform_ms,
|
|
291
|
+
}))
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
ingested.push(...chunk);
|
|
295
|
+
} catch (e) {
|
|
296
|
+
this.logger.error(
|
|
297
|
+
{ error: e, count: chunk.length, Category: 'sp00ky-client::StreamProcessorService::ingestMany' },
|
|
298
|
+
'Ingesting chunk into ssp failed'
|
|
299
|
+
);
|
|
300
|
+
}
|
|
156
301
|
}
|
|
157
302
|
} finally {
|
|
158
303
|
this.flushCoalescing();
|
|
159
304
|
}
|
|
305
|
+
this.logger.debug(
|
|
306
|
+
{ count: records.length, ingested: ingested.length, Category: 'sp00ky-client::StreamProcessorService::ingestMany' },
|
|
307
|
+
'Ingested batch into ssp'
|
|
308
|
+
);
|
|
309
|
+
this.markSnapshotDirty(ingested.length);
|
|
310
|
+
return ingested;
|
|
160
311
|
}
|
|
161
312
|
|
|
162
313
|
/**
|
|
@@ -187,10 +338,6 @@ export class StreamProcessorService {
|
|
|
187
338
|
if (buffered.length > 0) {
|
|
188
339
|
this.dispatchUpdates(buffered);
|
|
189
340
|
}
|
|
190
|
-
// The processor state after the last ingest is cumulative, so a single
|
|
191
|
-
// snapshot covers the whole batch. Kept fire-and-forget like the per-ingest
|
|
192
|
-
// call it replaces.
|
|
193
|
-
this.saveState();
|
|
194
341
|
}
|
|
195
342
|
|
|
196
343
|
/**
|
|
@@ -208,9 +355,7 @@ export class StreamProcessorService {
|
|
|
208
355
|
await init(); // Initialize the WASM module (web target)
|
|
209
356
|
// We cast the generated Sp00kyProcessor to our interface which is safer
|
|
210
357
|
this.processor = new Sp00kyProcessor() as unknown as WasmProcessor;
|
|
211
|
-
|
|
212
|
-
// Try to load state
|
|
213
|
-
await this.loadState();
|
|
358
|
+
this.applyProjection();
|
|
214
359
|
|
|
215
360
|
this.isInitialized = true;
|
|
216
361
|
this.logger.info(
|
|
@@ -226,47 +371,448 @@ export class StreamProcessorService {
|
|
|
226
371
|
}
|
|
227
372
|
}
|
|
228
373
|
|
|
229
|
-
|
|
230
|
-
|
|
374
|
+
/**
|
|
375
|
+
* Drop the current WASM processor and start a fresh, empty circuit. Used on
|
|
376
|
+
* local-bucket switches: the old circuit holds the previous user's rows AND
|
|
377
|
+
* views registered with the previous `$auth` context, so neither may survive.
|
|
378
|
+
* Deliberately loads nothing: the snapshot in the store being swapped away
|
|
379
|
+
* from belongs to the previous bucket; the caller primes the new bucket's
|
|
380
|
+
* circuit (`primeFromLocal`) once its store is open, and the DataModule
|
|
381
|
+
* rebind re-registers every live view against this fresh processor. Caller
|
|
382
|
+
* must re-seed `setPermissions` afterwards (a fresh circuit default-denies
|
|
383
|
+
* every table).
|
|
384
|
+
*/
|
|
385
|
+
async reset(): Promise<void> {
|
|
386
|
+
if (!this.isInitialized) return;
|
|
387
|
+
this.stateGeneration++;
|
|
388
|
+
this.batching = false;
|
|
389
|
+
this.batchBuffer.clear();
|
|
390
|
+
this.snapshotDirty = false;
|
|
391
|
+
this.dirtyRows = 0;
|
|
392
|
+
this.widenPending.clear();
|
|
393
|
+
const previous = this.processor;
|
|
394
|
+
this.processor = new Sp00kyProcessor() as unknown as WasmProcessor;
|
|
395
|
+
this.applyProjection();
|
|
396
|
+
this.freeProcessor(previous);
|
|
397
|
+
this.logger.info(
|
|
398
|
+
{ Category: 'sp00ky-client::StreamProcessorService::reset' },
|
|
399
|
+
'Stream processor reset (fresh circuit)'
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Release the wasm circuit and stop checkpointing. Call when the client is
|
|
405
|
+
* torn down; a recreated client (provider remount, HMR) would otherwise stack
|
|
406
|
+
* one full circuit per instance.
|
|
407
|
+
*/
|
|
408
|
+
dispose(): void {
|
|
409
|
+
this.stopCheckpoints();
|
|
410
|
+
const previous = this.processor;
|
|
411
|
+
this.processor = undefined;
|
|
412
|
+
this.isInitialized = false;
|
|
413
|
+
this.batching = false;
|
|
414
|
+
this.batchBuffer.clear();
|
|
415
|
+
this.receivers = [];
|
|
416
|
+
this.freeProcessor(previous);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
|
|
421
|
+
* not expose `free`, and a double free must not take the app down.
|
|
422
|
+
*/
|
|
423
|
+
private freeProcessor(processor: WasmProcessor | undefined): void {
|
|
424
|
+
if (!processor || typeof processor.free !== 'function') return;
|
|
231
425
|
try {
|
|
232
|
-
|
|
426
|
+
processor.free();
|
|
427
|
+
} catch (e) {
|
|
428
|
+
this.logger.debug(
|
|
429
|
+
{ error: e, Category: 'sp00ky-client::StreamProcessorService::freeProcessor' },
|
|
430
|
+
'Failed to free previous wasm circuit'
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
233
434
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
435
|
+
/** Toggle circuit-state persistence (shared-tabs follower/leader role). */
|
|
436
|
+
setPersistenceEnabled(enabled: boolean): void {
|
|
437
|
+
this.persistState = enabled;
|
|
438
|
+
if (!enabled) this.stopCheckpoints();
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Snapshot persistence (`persistCircuit`). When on, the circuit's store is
|
|
443
|
+
* written to the local store on a checkpoint interval and when the page
|
|
444
|
+
* goes hidden, and restored by {@link primeFromLocal} on the next boot.
|
|
445
|
+
*/
|
|
446
|
+
configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void {
|
|
447
|
+
this.persistCircuit = enabled;
|
|
448
|
+
if (checkpointMs && checkpointMs > 0) this.checkpointMs = checkpointMs;
|
|
449
|
+
if (!enabled) this.stopCheckpoints();
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Field projection (`circuitProjection`, default on). Takes effect on the
|
|
454
|
+
* next processor (`init`/`reset`) and on rows written after that.
|
|
455
|
+
*/
|
|
456
|
+
configureProjection(enabled: boolean): void {
|
|
457
|
+
this.projection = enabled;
|
|
458
|
+
this.applyProjection();
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
private applyProjection(): void {
|
|
462
|
+
if (!this.processor || typeof this.processor.set_projection !== 'function') return;
|
|
463
|
+
try {
|
|
464
|
+
this.processor.set_projection(this.projection);
|
|
465
|
+
} catch (e) {
|
|
466
|
+
this.logger.warn(
|
|
467
|
+
{ error: e, Category: 'sp00ky-client::StreamProcessorService::applyProjection' },
|
|
468
|
+
'set_projection failed'
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Resolves once the boot-time prime has finished (or was skipped). */
|
|
474
|
+
whenPrimed(): Promise<void> {
|
|
475
|
+
return this.primed;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Fill the circuit from the LOCAL store, in the background.
|
|
480
|
+
*
|
|
481
|
+
* With a usable snapshot: install it under whatever views have registered
|
|
482
|
+
* meanwhile (`load_store_state` re-primes them), then `reconcile` each table
|
|
483
|
+
* against the store's `(id, rv)` list so rows deleted since the checkpoint
|
|
484
|
+
* are stepped out and only rows added or changed since are read back and
|
|
485
|
+
* ingested. Without one: read every row and ingest it, chunked.
|
|
486
|
+
*
|
|
487
|
+
* Either way the circuit ends up equal to the local store without touching
|
|
488
|
+
* the network, so the first sync diff is a real delta rather than "fetch
|
|
489
|
+
* everything". The returned promise never rejects; `whenPrimed` gates on it.
|
|
490
|
+
*/
|
|
491
|
+
primeFromLocal(ctx: CircuitPrimeContext): Promise<void> {
|
|
492
|
+
this.schemaHash = ctx.schemaHash;
|
|
493
|
+
const run = this.runPrime(ctx).catch((e) => {
|
|
494
|
+
this.logger.warn(
|
|
495
|
+
{ error: e, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
|
|
496
|
+
'Circuit prime failed; the circuit fills from sync instead'
|
|
497
|
+
);
|
|
498
|
+
});
|
|
499
|
+
this.primed = run;
|
|
500
|
+
return run;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
private async runPrime(ctx: CircuitPrimeContext): Promise<void> {
|
|
504
|
+
const processor = this.processor;
|
|
505
|
+
if (!processor || typeof this.db.scanVersions !== 'function') return;
|
|
506
|
+
const generation = this.stateGeneration;
|
|
507
|
+
const epoch = this.db.epoch;
|
|
508
|
+
// A bucket switch replaces the processor and the store under us; every
|
|
509
|
+
// step re-checks so a stale chunk never lands in the new bucket.
|
|
510
|
+
const alive = () =>
|
|
511
|
+
this.processor === processor && generation === this.stateGeneration && epoch === this.db.epoch;
|
|
512
|
+
const t0 = performance.now();
|
|
513
|
+
|
|
514
|
+
// Before anything reads a version: a table whose columns changed since its
|
|
515
|
+
// bodies were cached reads as stale from here on (see sqlite-column-reset).
|
|
516
|
+
if (ctx.columnFingerprints && typeof this.db.resetChangedTables === 'function') {
|
|
517
|
+
try {
|
|
518
|
+
const reset = await this.db.resetChangedTables(ctx.columnFingerprints, ctx.pendingIds);
|
|
519
|
+
if (!alive()) return;
|
|
520
|
+
if (reset.length > 0) {
|
|
521
|
+
this.logger.info(
|
|
522
|
+
{ tables: reset, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
|
|
523
|
+
'Columns changed since these rows were cached; they will be fetched again'
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
} catch (e) {
|
|
527
|
+
this.logger.warn(
|
|
528
|
+
{ error: e, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
|
|
529
|
+
'Column change check failed; cached versions kept'
|
|
249
530
|
);
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
let restored = false;
|
|
535
|
+
if (
|
|
536
|
+
this.persistCircuit &&
|
|
537
|
+
typeof this.db.getSnapshot === 'function' &&
|
|
538
|
+
typeof processor.load_store_state === 'function'
|
|
539
|
+
) {
|
|
540
|
+
const snapshot = await this.db.getSnapshot(CIRCUIT_SNAPSHOT_KEY);
|
|
541
|
+
if (!alive()) return;
|
|
542
|
+
if (snapshot) {
|
|
543
|
+
const { meta } = snapshot;
|
|
544
|
+
if (meta.formatVersion !== CIRCUIT_SNAPSHOT_FORMAT || meta.schemaHash !== ctx.schemaHash) {
|
|
545
|
+
this.logger.info(
|
|
546
|
+
{ meta, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
|
|
547
|
+
'Circuit snapshot is from another format or schema; priming from rows'
|
|
258
548
|
);
|
|
549
|
+
} else {
|
|
550
|
+
try {
|
|
551
|
+
const tLoad = performance.now();
|
|
552
|
+
const updates = processor.load_store_state(snapshot.bytes);
|
|
553
|
+
this.dispatchWasmUpdates(updates);
|
|
554
|
+
restored = true;
|
|
555
|
+
this.logger.info(
|
|
556
|
+
{
|
|
557
|
+
bytes: snapshot.bytes.byteLength,
|
|
558
|
+
views: updates.length,
|
|
559
|
+
loadMs: Math.round(performance.now() - tLoad),
|
|
560
|
+
Category: 'sp00ky-client::StreamProcessorService::primeFromLocal',
|
|
561
|
+
},
|
|
562
|
+
'Circuit snapshot restored'
|
|
563
|
+
);
|
|
564
|
+
} catch (e) {
|
|
565
|
+
this.logger.warn(
|
|
566
|
+
{ error: e, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
|
|
567
|
+
'Circuit snapshot unreadable; priming from rows'
|
|
568
|
+
);
|
|
569
|
+
}
|
|
259
570
|
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// Read the versions AFTER the snapshot: a batch the leader writes between
|
|
575
|
+
// the two can only make the store side newer, which reconcile handles.
|
|
576
|
+
const versions = await this.db.scanVersions(ctx.tables);
|
|
577
|
+
if (!alive()) return;
|
|
578
|
+
const total = Object.values(versions).reduce((n, v) => n + v.length, 0);
|
|
579
|
+
if (!restored && this.db.engineKind !== 'sqlite' && total > SURREAL_PRIME_ROW_CAP) {
|
|
580
|
+
this.logger.warn(
|
|
581
|
+
{ total, cap: SURREAL_PRIME_ROW_CAP, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
|
|
582
|
+
'Too many cached rows to prime through the main-thread engine; circuit fills from sync'
|
|
583
|
+
);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let ingested = 0;
|
|
588
|
+
let fetched = 0;
|
|
589
|
+
let deleted = 0;
|
|
590
|
+
for (const table of ctx.tables) {
|
|
591
|
+
const entries = versions[table] ?? [];
|
|
592
|
+
let toFetch: string[];
|
|
593
|
+
if (restored && typeof processor.reconcile === 'function') {
|
|
594
|
+
const result = processor.reconcile(table, entries);
|
|
595
|
+
this.dispatchWasmUpdates(result.updates);
|
|
596
|
+
deleted += result.deleted;
|
|
597
|
+
toFetch = result.fetch;
|
|
260
598
|
} else {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
599
|
+
toFetch = entries.map(([id]) => id);
|
|
600
|
+
}
|
|
601
|
+
for (const chunk of chunks(toFetch, PRIME_CHUNK)) {
|
|
602
|
+
const rows = await this.db.selectByIds(table, chunk);
|
|
603
|
+
if (!alive()) return;
|
|
604
|
+
fetched += rows.length;
|
|
605
|
+
ingested += this.ingestMany(
|
|
606
|
+
rows.map((row) => ({
|
|
607
|
+
table,
|
|
608
|
+
op: 'CREATE' as const,
|
|
609
|
+
id: idString(row.id),
|
|
610
|
+
record: row,
|
|
611
|
+
}))
|
|
612
|
+
).length;
|
|
613
|
+
}
|
|
614
|
+
if (entries.length > 0) {
|
|
615
|
+
ctx.onVersions?.(
|
|
616
|
+
table,
|
|
617
|
+
entries.filter(([id]) => !ctx.pendingIds.has(id))
|
|
264
618
|
);
|
|
265
619
|
}
|
|
620
|
+
}
|
|
621
|
+
// A prime from rows leaves the store with no snapshot to fall back on;
|
|
622
|
+
// let the next checkpoint write one even if nothing else changes.
|
|
623
|
+
if (!restored && ingested > 0) this.markSnapshotDirty(Math.max(ingested, CHECKPOINT_MIN_ROWS));
|
|
624
|
+
this.logger.info(
|
|
625
|
+
{
|
|
626
|
+
restored,
|
|
627
|
+
rows: total,
|
|
628
|
+
fetched,
|
|
629
|
+
ingested,
|
|
630
|
+
deleted,
|
|
631
|
+
ms: Math.round(performance.now() - t0),
|
|
632
|
+
Category: 'sp00ky-client::StreamProcessorService::primeFromLocal',
|
|
633
|
+
},
|
|
634
|
+
'Circuit primed from the local store'
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** Publish wasm updates produced outside an ingest (restore, reconcile). */
|
|
639
|
+
private dispatchWasmUpdates(updates: WasmStreamUpdate[] | undefined): void {
|
|
640
|
+
if (!updates || updates.length === 0) return;
|
|
641
|
+
this.dispatchUpdates(
|
|
642
|
+
updates.map((u) => ({
|
|
643
|
+
queryHash: u.query_id,
|
|
644
|
+
localArray: u.result_data,
|
|
645
|
+
op: 'CREATE' as const,
|
|
646
|
+
}))
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* Record that the circuit changed by `rows` rows. Cheap; the snapshot is
|
|
652
|
+
* deferred to the checkpoint timer and skipped entirely when `persistCircuit`
|
|
653
|
+
* is off.
|
|
654
|
+
*/
|
|
655
|
+
private markSnapshotDirty(rows = 1): void {
|
|
656
|
+
if (!this.persistCircuit || !this.persistState) return;
|
|
657
|
+
this.snapshotDirty = true;
|
|
658
|
+
this.dirtyRows += rows;
|
|
659
|
+
this.startCheckpoints();
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private startCheckpoints(): void {
|
|
663
|
+
if (this.checkpointTimer) return;
|
|
664
|
+
this.checkpointTimer = setInterval(() => {
|
|
665
|
+
if (!this.snapshotDirty || this.dirtyRows < CHECKPOINT_MIN_ROWS) return;
|
|
666
|
+
void this.checkpoint('interval');
|
|
667
|
+
}, this.checkpointMs);
|
|
668
|
+
// Node/test environments have no `window`; the interval alone is enough there.
|
|
669
|
+
if (typeof window !== 'undefined' && !this.hideHandler) {
|
|
670
|
+
// `visibilitychange: hidden` is the reliable last chance: a 100 MB write
|
|
671
|
+
// cannot finish inside `pagehide`, which is kept only as best effort.
|
|
672
|
+
this.hideHandler = () => {
|
|
673
|
+
if (!this.snapshotDirty) return;
|
|
674
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'visible') return;
|
|
675
|
+
void this.checkpoint('hidden');
|
|
676
|
+
};
|
|
677
|
+
window.addEventListener('visibilitychange', this.hideHandler);
|
|
678
|
+
window.addEventListener('pagehide', this.hideHandler);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** Stop checkpointing and drop the visibility listeners. */
|
|
683
|
+
stopCheckpoints(): void {
|
|
684
|
+
if (this.checkpointTimer) {
|
|
685
|
+
clearInterval(this.checkpointTimer);
|
|
686
|
+
this.checkpointTimer = null;
|
|
687
|
+
}
|
|
688
|
+
if (this.hideHandler && typeof window !== 'undefined') {
|
|
689
|
+
window.removeEventListener('visibilitychange', this.hideHandler);
|
|
690
|
+
window.removeEventListener('pagehide', this.hideHandler);
|
|
691
|
+
}
|
|
692
|
+
this.hideHandler = null;
|
|
693
|
+
this.snapshotDirty = false;
|
|
694
|
+
this.dirtyRows = 0;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Write the circuit's store to the local store as a snapshot. Compacts the
|
|
699
|
+
* row arena first when dead bytes outweigh live ones. Serialised: a second
|
|
700
|
+
* call while one is in flight joins it. No-op unless persistence is on, this
|
|
701
|
+
* tab owns the store, and the engine can hold a snapshot.
|
|
702
|
+
*/
|
|
703
|
+
checkpoint(reason = 'manual'): Promise<void> {
|
|
704
|
+
if (this.checkpointInFlight) return this.checkpointInFlight;
|
|
705
|
+
const run = this.runCheckpoint(reason).finally(() => {
|
|
706
|
+
this.checkpointInFlight = null;
|
|
707
|
+
});
|
|
708
|
+
this.checkpointInFlight = run;
|
|
709
|
+
return run;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
private async runCheckpoint(reason: string): Promise<void> {
|
|
713
|
+
const processor = this.processor;
|
|
714
|
+
if (!processor || !this.persistState || !this.persistCircuit || !this.schemaHash) return;
|
|
715
|
+
if (typeof this.db.putSnapshot !== 'function' || typeof processor.save_store_state !== 'function') {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
const generation = this.stateGeneration;
|
|
719
|
+
const epoch = this.db.epoch;
|
|
720
|
+
const rows = this.dirtyRows;
|
|
721
|
+
this.snapshotDirty = false;
|
|
722
|
+
this.dirtyRows = 0;
|
|
723
|
+
try {
|
|
724
|
+
const t0 = performance.now();
|
|
725
|
+
let reclaimed = 0;
|
|
726
|
+
if (
|
|
727
|
+
typeof processor.compact === 'function' &&
|
|
728
|
+
typeof processor.dead_bytes === 'function' &&
|
|
729
|
+
typeof processor.live_bytes === 'function'
|
|
730
|
+
) {
|
|
731
|
+
const dead = processor.dead_bytes();
|
|
732
|
+
if (dead > 1_000_000 && dead > processor.live_bytes()) reclaimed = processor.compact();
|
|
733
|
+
}
|
|
734
|
+
const bytes = processor.save_store_state();
|
|
735
|
+
const meta = {
|
|
736
|
+
formatVersion: CIRCUIT_SNAPSHOT_FORMAT,
|
|
737
|
+
schemaHash: this.schemaHash,
|
|
738
|
+
savedAt: Date.now(),
|
|
739
|
+
maxRv: typeof processor.max_row_versions === 'function' ? processor.max_row_versions() : undefined,
|
|
740
|
+
};
|
|
741
|
+
// A reset or bucket switch landed while we serialised: this snapshot
|
|
742
|
+
// describes the OLD bucket's circuit and must not be written into the
|
|
743
|
+
// new bucket's store.
|
|
744
|
+
if (generation !== this.stateGeneration || epoch !== this.db.epoch) return;
|
|
745
|
+
await this.db.putSnapshot(CIRCUIT_SNAPSHOT_KEY, bytes, meta);
|
|
746
|
+
this.logger.info(
|
|
747
|
+
{
|
|
748
|
+
reason,
|
|
749
|
+
rows,
|
|
750
|
+
bytes: bytes.byteLength,
|
|
751
|
+
reclaimed,
|
|
752
|
+
ms: Math.round(performance.now() - t0),
|
|
753
|
+
Category: 'sp00ky-client::StreamProcessorService::checkpoint',
|
|
754
|
+
},
|
|
755
|
+
'Circuit snapshot written'
|
|
756
|
+
);
|
|
266
757
|
} catch (e) {
|
|
267
|
-
this.logger.
|
|
268
|
-
{ error: e, Category: 'sp00ky-client::StreamProcessorService::
|
|
269
|
-
'
|
|
758
|
+
this.logger.warn(
|
|
759
|
+
{ error: e, reason, Category: 'sp00ky-client::StreamProcessorService::checkpoint' },
|
|
760
|
+
'Circuit snapshot failed'
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Projection widening: a newly registered view evaluates fields that rows
|
|
767
|
+
* already in the circuit were stored without. Merge just those fields in,
|
|
768
|
+
* table by table, from the local store. The view registered against what
|
|
769
|
+
* was present and converges as the merges step through.
|
|
770
|
+
*/
|
|
771
|
+
private scheduleWiden(missing: Record<string, string[]>): void {
|
|
772
|
+
for (const [table, fields] of Object.entries(missing)) {
|
|
773
|
+
const set = this.widenPending.get(table) ?? new Set<string>();
|
|
774
|
+
for (const f of fields) set.add(f);
|
|
775
|
+
this.widenPending.set(table, set);
|
|
776
|
+
}
|
|
777
|
+
this.widenQueue = this.widenQueue.then(() => this.runWiden()).catch((e) => {
|
|
778
|
+
this.logger.warn(
|
|
779
|
+
{ error: e, Category: 'sp00ky-client::StreamProcessorService::widen' },
|
|
780
|
+
'Projection widening failed'
|
|
781
|
+
);
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
private async runWiden(): Promise<void> {
|
|
786
|
+
const processor = this.processor;
|
|
787
|
+
if (!processor || typeof this.db.scanVersions !== 'function') {
|
|
788
|
+
this.widenPending.clear();
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
const generation = this.stateGeneration;
|
|
792
|
+
const epoch = this.db.epoch;
|
|
793
|
+
while (this.widenPending.size > 0) {
|
|
794
|
+
const [table, fields] = this.widenPending.entries().next().value as [string, Set<string>];
|
|
795
|
+
this.widenPending.delete(table);
|
|
796
|
+
const select = Array.from(fields);
|
|
797
|
+
const versions = await this.db.scanVersions([table]);
|
|
798
|
+
if (this.processor !== processor || generation !== this.stateGeneration || epoch !== this.db.epoch) return;
|
|
799
|
+
const ids = (versions[table] ?? []).map(([id]) => id);
|
|
800
|
+
let merged = 0;
|
|
801
|
+
for (const chunk of chunks(ids, PRIME_CHUNK)) {
|
|
802
|
+
const rows = await this.db.selectByIds(table, chunk, { select });
|
|
803
|
+
if (this.processor !== processor || generation !== this.stateGeneration || epoch !== this.db.epoch) return;
|
|
804
|
+
merged += this.ingestMany(
|
|
805
|
+
rows.map((row) => ({
|
|
806
|
+
table,
|
|
807
|
+
op: 'MERGE' as const,
|
|
808
|
+
id: idString(row.id),
|
|
809
|
+
record: row,
|
|
810
|
+
}))
|
|
811
|
+
).length;
|
|
812
|
+
}
|
|
813
|
+
this.logger.info(
|
|
814
|
+
{ table, fields: select, merged, Category: 'sp00ky-client::StreamProcessorService::widen' },
|
|
815
|
+
'Widened projected rows with newly evaluated fields'
|
|
270
816
|
);
|
|
271
817
|
}
|
|
272
818
|
}
|
|
@@ -317,28 +863,6 @@ export class StreamProcessorService {
|
|
|
317
863
|
);
|
|
318
864
|
}
|
|
319
865
|
|
|
320
|
-
async saveState() {
|
|
321
|
-
if (!this.processor) return;
|
|
322
|
-
try {
|
|
323
|
-
// Assuming processor has a save_state method that returns the state string/bytes
|
|
324
|
-
if (typeof this.processor.save_state === 'function') {
|
|
325
|
-
const state = this.processor.save_state();
|
|
326
|
-
if (state) {
|
|
327
|
-
await this.persistenceClient.set('_00_stream_processor_state', state);
|
|
328
|
-
this.logger.trace(
|
|
329
|
-
{ Category: 'sp00ky-client::StreamProcessorService::saveState' },
|
|
330
|
-
'State saved'
|
|
331
|
-
);
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
} catch (e) {
|
|
335
|
-
this.logger.error(
|
|
336
|
-
{ error: e, Category: 'sp00ky-client::StreamProcessorService::saveState' },
|
|
337
|
-
'Failed to save state'
|
|
338
|
-
);
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
342
866
|
/**
|
|
343
867
|
* Ingest a record change into the processor.
|
|
344
868
|
* Emits 'stream_update' event if materialized views are affected.
|
|
@@ -346,7 +870,7 @@ export class StreamProcessorService {
|
|
|
346
870
|
*/
|
|
347
871
|
ingest(
|
|
348
872
|
table: string,
|
|
349
|
-
op: '
|
|
873
|
+
op: IngestRecord['op'],
|
|
350
874
|
id: string,
|
|
351
875
|
record: any
|
|
352
876
|
): WasmStreamUpdate[] {
|
|
@@ -390,7 +914,8 @@ export class StreamProcessorService {
|
|
|
390
914
|
const updates: StreamUpdate[] = rawUpdates.map((u: WasmStreamUpdate) => ({
|
|
391
915
|
queryHash: u.query_id,
|
|
392
916
|
localArray: u.result_data,
|
|
393
|
-
|
|
917
|
+
// A MERGE is a content update as far as consumers are concerned.
|
|
918
|
+
op: op === 'MERGE' ? 'UPDATE' : op,
|
|
394
919
|
materializationTimeMs,
|
|
395
920
|
storeApplyMs: u.timing_store_apply_ms,
|
|
396
921
|
circuitStepMs: u.timing_circuit_step_ms,
|
|
@@ -399,10 +924,10 @@ export class StreamProcessorService {
|
|
|
399
924
|
// Direct handler call instead of event
|
|
400
925
|
this.notifyUpdates(updates);
|
|
401
926
|
}
|
|
402
|
-
// While batching (inside `ingestMany`), `flushCoalescing`
|
|
403
|
-
// for the whole batch
|
|
927
|
+
// While batching (inside `ingestMany`), `flushCoalescing` marks dirty once
|
|
928
|
+
// for the whole batch, skip the redundant per-record mark here.
|
|
404
929
|
if (!this.batching) {
|
|
405
|
-
this.
|
|
930
|
+
this.markSnapshotDirty();
|
|
406
931
|
}
|
|
407
932
|
return rawUpdates;
|
|
408
933
|
} catch (e) {
|
|
@@ -479,7 +1004,9 @@ export class StreamProcessorService {
|
|
|
479
1004
|
snapshotMs: initialUpdate.timing_snapshot_ms ?? 0,
|
|
480
1005
|
},
|
|
481
1006
|
};
|
|
482
|
-
|
|
1007
|
+
if (initialUpdate.missing_fields && Object.keys(initialUpdate.missing_fields).length > 0) {
|
|
1008
|
+
this.scheduleWiden(initialUpdate.missing_fields);
|
|
1009
|
+
}
|
|
483
1010
|
this.logger.debug(
|
|
484
1011
|
{
|
|
485
1012
|
queryHash: queryPlan.queryHash,
|
|
@@ -506,7 +1033,6 @@ export class StreamProcessorService {
|
|
|
506
1033
|
if (!this.processor) return;
|
|
507
1034
|
try {
|
|
508
1035
|
this.processor.unregister_view(queryHash);
|
|
509
|
-
this.saveState();
|
|
510
1036
|
} catch (e) {
|
|
511
1037
|
this.logger.error(
|
|
512
1038
|
{ error: e, Category: 'sp00ky-client::StreamProcessorService::unregisterQueryPlan' },
|
|
@@ -543,7 +1069,9 @@ export class StreamProcessorService {
|
|
|
543
1069
|
const isNotPlainObject = value.constructor !== Object;
|
|
544
1070
|
|
|
545
1071
|
if (hasTable && hasId && hasToString && isNotPlainObject) {
|
|
546
|
-
|
|
1072
|
+
// The raw `table:id`, as the store spells it. `toString()` is escaped
|
|
1073
|
+
// SurrealQL (SDK 2.1.0: `game:⟨476g…⟩`); only a complex key uses it.
|
|
1074
|
+
const result = recordIdKey(value) ?? value.toString();
|
|
547
1075
|
this.logger.trace(
|
|
548
1076
|
{ result, Category: 'sp00ky-client::StreamProcessorService::normalizeValue' },
|
|
549
1077
|
'RecordId detected'
|