@spooky-sync/core 0.0.1-canary.20 → 0.0.1-canary.201
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 +57 -0
- package/dist/index.d.ts +2184 -54
- package/dist/index.js +11515 -2399
- package/dist/otel/index.d.ts +2 -2
- package/dist/otel/index.js +6 -6
- package/dist/sqlite-open.js +276 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +421 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +434 -0
- package/dist/types.d.ts +688 -11
- package/package.json +11 -7
- package/scripts/check-broker-bundle.mjs +33 -0
- package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
- package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
- package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
- package/src/bucket-blurhash.test.ts +148 -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 +35 -2
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +201 -0
- package/src/modules/auth/events/index.ts +2 -1
- package/src/modules/auth/index.ts +59 -20
- package/src/modules/cache/index.ts +112 -32
- package/src/modules/cache/types.ts +2 -2
- package/src/modules/crdt/crdt-field.ts +294 -0
- package/src/modules/crdt/crdt-hydration.test.ts +210 -0
- package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
- package/src/modules/crdt/index.ts +463 -0
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/data/data.hydration.test.ts +142 -0
- package/src/modules/data/data.membership.test.ts +462 -0
- package/src/modules/data/data.rebind.test.ts +147 -0
- package/src/modules/data/data.run.test.ts +113 -0
- package/src/modules/data/data.settled-writes.test.ts +206 -0
- package/src/modules/data/data.status.test.ts +249 -0
- package/src/modules/data/id-set-plan.test.ts +122 -0
- package/src/modules/data/index.ts +1580 -130
- package/src/modules/data/mutation-id.test.ts +25 -0
- package/src/modules/data/mutation-id.ts +35 -0
- package/src/modules/data/window-query.test.ts +52 -0
- package/src/modules/data/window-query.ts +194 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +386 -37
- package/src/modules/devtools/notify-throttle.test.ts +149 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +168 -0
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +110 -0
- package/src/modules/feature-flag/index.test.ts +251 -0
- package/src/modules/feature-flag/index.ts +308 -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.test.ts +107 -0
- package/src/modules/sync/queue/queue-down.ts +35 -6
- package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
- package/src/modules/sync/queue/queue-up.ts +241 -57
- package/src/modules/sync/scheduler.pause.test.ts +109 -0
- package/src/modules/sync/scheduler.retry.test.ts +156 -0
- package/src/modules/sync/scheduler.ts +158 -11
- package/src/modules/sync/sync.cleanup.test.ts +116 -0
- package/src/modules/sync/sync.health.test.ts +149 -0
- package/src/modules/sync/sync.heartbeat.test.ts +80 -0
- package/src/modules/sync/sync.live-removal.test.ts +134 -0
- package/src/modules/sync/sync.reconnect.test.ts +145 -0
- package/src/modules/sync/sync.subquery.test.ts +82 -0
- package/src/modules/sync/sync.ts +1558 -99
- package/src/modules/sync/utils.test.ts +269 -2
- package/src/modules/sync/utils.ts +201 -17
- package/src/otel/index.ts +13 -10
- 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 +160 -0
- package/src/services/database/connection-supervisor.test.ts +289 -0
- package/src/services/database/connection-supervisor.ts +415 -0
- package/src/services/database/database.query-timeout.test.ts +83 -0
- package/src/services/database/database.ts +32 -12
- package/src/services/database/engine-factory.ts +33 -0
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/index.ts +7 -0
- package/src/services/database/local-migrator.ts +30 -27
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +478 -67
- 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 +413 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +110 -14
- package/src/services/database/sqlite-cache-engine.test.ts +558 -0
- package/src/services/database/sqlite-cache-engine.ts +1257 -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-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +104 -0
- package/src/services/database/sqlite-plan-sql.ts +106 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +246 -0
- package/src/services/database/sqlite-select.ts +121 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +221 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +416 -0
- package/src/services/database/surreal-cache-engine.ts +141 -0
- package/src/services/logger/index.ts +3 -2
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +11 -4
- package/src/services/persistence/surrealdb.ts +10 -10
- package/src/services/stream-processor/index.ts +444 -52
- 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 +216 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +23 -2
- package/src/services/tabs/broker-client.ts +283 -0
- package/src/services/tabs/broker.test.ts +278 -0
- package/src/services/tabs/coordinator.test.ts +244 -0
- package/src/services/tabs/coordinator.ts +576 -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 +242 -0
- package/src/services/tabs/support.ts +36 -0
- package/src/services/tabs/tabs-broker-worker.ts +586 -0
- package/src/sp00ky.auth-order.test.ts +92 -0
- package/src/sp00ky.init-query.test.ts +183 -0
- package/src/sp00ky.ts +1543 -0
- package/src/types.ts +496 -13
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/error-classification.test.ts +44 -0
- package/src/utils/error-classification.ts +7 -0
- package/src/utils/index.ts +73 -13
- package/src/utils/parser.ts +3 -2
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/surql.ts +30 -18
- package/src/utils/withRetry.test.ts +1 -1
- package/tsdown.config.ts +86 -1
- package/src/spooky.ts +0 -395
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Client-side mirror of `packages/ssp-protocol/src/lib.rs`'s
|
|
2
|
+
// `query_table_for` / `list_ref_table_for`. Same naming convention so
|
|
3
|
+
// the LIVE subscription, the initial-fetch read, and the SSP's writes
|
|
4
|
+
// all land on the same table.
|
|
5
|
+
//
|
|
6
|
+
// The mode is currently hardcoded to `dedicated` because that's the
|
|
7
|
+
// only mode the e2e suite exercises and threading the value through
|
|
8
|
+
// codegen wasn't necessary to land the cross-session fix. If single
|
|
9
|
+
// mode ever needs to be exposed from the TS client too, the SSP server
|
|
10
|
+
// already reads it from `SPKY_SSP_REF_MODE`; add a matching codegen
|
|
11
|
+
// export then.
|
|
12
|
+
|
|
13
|
+
import { cyrb53 } from '@spooky-sync/query-builder';
|
|
14
|
+
|
|
15
|
+
export type RefMode = 'single' | 'dedicated';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Sentinel user id for unauthenticated clients when anonymous live queries are
|
|
19
|
+
* enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
|
|
20
|
+
* so it can never collide with a real user id (those arrive as `user:<id>`);
|
|
21
|
+
* both sides resolve it to the shared `_00_list_ref_anon` table.
|
|
22
|
+
*/
|
|
23
|
+
export const ANON_USER_ID = 'anon';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Default ref-storage mode for this client build. Mirrors the SSP's
|
|
27
|
+
* default (`RefMode::Dedicated`) so cross-session sync works out of the
|
|
28
|
+
* box.
|
|
29
|
+
*/
|
|
30
|
+
export const DEFAULT_REF_MODE: RefMode = 'dedicated';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Sanitize a user record id (e.g. `"user:abc"`) into the segment that
|
|
34
|
+
* goes into a dedicated table name (e.g. `"abc"`). Returns `null` if
|
|
35
|
+
* the id is missing the `user:` prefix or contains characters that
|
|
36
|
+
* aren't valid in a SurrealDB table identifier — the server-side
|
|
37
|
+
* `ssp_protocol::sanitize_user_id` uses the same predicate.
|
|
38
|
+
*
|
|
39
|
+
* Accepts both string ids (`"user:abc"`) and SurrealDB `RecordId`
|
|
40
|
+
* objects (which only stringify cleanly via `.toString()`), since
|
|
41
|
+
* `AuthService` passes the record-id object as-is to its subscribers.
|
|
42
|
+
*/
|
|
43
|
+
export function sanitizeUserId(userId: unknown): string | null {
|
|
44
|
+
if (userId === null || userId === undefined) return null;
|
|
45
|
+
const asString =
|
|
46
|
+
typeof userId === 'string'
|
|
47
|
+
? userId
|
|
48
|
+
: typeof (userId as { toString?: unknown }).toString === 'function'
|
|
49
|
+
? (userId as { toString: () => string }).toString()
|
|
50
|
+
: null;
|
|
51
|
+
if (!asString) return null;
|
|
52
|
+
const raw = asString.startsWith('user:') ? asString.slice('user:'.length) : asString;
|
|
53
|
+
if (raw.length === 0) return null;
|
|
54
|
+
if (!/^[A-Za-z0-9_]+$/.test(raw)) return null;
|
|
55
|
+
return raw;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Resolve the LOCAL storage bucket id for a user. Every user gets their own
|
|
60
|
+
* IndexedDB-backed local store (`indxdb://sp00ky-<bucketId>`) so cached rows,
|
|
61
|
+
* query state, and the mutation outbox never leak across accounts on a shared
|
|
62
|
+
* device. Signed-out sessions share the `anon` bucket.
|
|
63
|
+
*
|
|
64
|
+
* An id that fails sanitization still gets a DETERMINISTIC per-user bucket
|
|
65
|
+
* (cyrb53 hex of the raw id) — falling back to `anon` here would put an
|
|
66
|
+
* authenticated user in the shared bucket and recreate the cross-user leak.
|
|
67
|
+
*/
|
|
68
|
+
export function bucketIdForUser(userId: unknown): string {
|
|
69
|
+
if (userId === null || userId === undefined || userId === ANON_USER_ID) return ANON_USER_ID;
|
|
70
|
+
const uid = sanitizeUserId(userId);
|
|
71
|
+
if (uid) return uid;
|
|
72
|
+
return `u${cyrb53(String(userId)).toString(16)}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Returns the `_00_list_ref` table name for `(mode, userId)`. Falls
|
|
77
|
+
* back to the global `_00_list_ref` when sanitization fails or in
|
|
78
|
+
* single mode.
|
|
79
|
+
*/
|
|
80
|
+
export function listRefTableFor(mode: RefMode, userId: unknown): string {
|
|
81
|
+
// Anonymous clients (flag-enabled) share one dedicated table in both modes —
|
|
82
|
+
// checked before the mode split so it never lands on the per-user or the
|
|
83
|
+
// auth-gated global table. Matches `ssp_protocol::list_ref_table_for`.
|
|
84
|
+
if (userId === ANON_USER_ID) return '_00_list_ref_anon';
|
|
85
|
+
if (mode === 'single') return '_00_list_ref';
|
|
86
|
+
const uid = sanitizeUserId(userId);
|
|
87
|
+
return uid ? `_00_list_ref_user_${uid}` : '_00_list_ref';
|
|
88
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { RecordId } from 'surrealdb';
|
|
2
|
-
import { SchemaStructure } from '@spooky-sync/query-builder';
|
|
3
|
-
import { RemoteDatabaseService } from '../../services/database/index';
|
|
4
|
-
import { CacheModule, CacheRecord, RecordWithId } from '../cache/index';
|
|
5
|
-
import { RecordVersionDiff } from '../../types';
|
|
6
|
-
import { Logger } from '../../services/logger/index';
|
|
1
|
+
import type { RecordId } from 'surrealdb';
|
|
2
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
3
|
+
import type { RemoteDatabaseService } from '../../services/database/index';
|
|
4
|
+
import type { CacheModule, CacheRecord, RecordWithId } from '../cache/index';
|
|
5
|
+
import type { RecordVersionDiff } from '../../types';
|
|
6
|
+
import type { Logger } from '../../services/logger/index';
|
|
7
7
|
import { SyncEventTypes, createSyncEventSystem } from './events/index';
|
|
8
8
|
import { encodeRecordId } from '../../utils/index';
|
|
9
9
|
import { cleanRecord } from '../../utils/parser';
|
|
@@ -12,7 +12,7 @@ import { cleanRecord } from '../../utils/parser';
|
|
|
12
12
|
* SyncEngine handles the core sync operations: fetching remote records,
|
|
13
13
|
* caching them locally, and ingesting into DBSP.
|
|
14
14
|
*
|
|
15
|
-
* This is extracted from
|
|
15
|
+
* This is extracted from Sp00kySync to separate "how to sync" from "when to sync".
|
|
16
16
|
*/
|
|
17
17
|
export class SyncEngine {
|
|
18
18
|
private logger: Logger;
|
|
@@ -24,7 +24,7 @@ export class SyncEngine {
|
|
|
24
24
|
private schema: SchemaStructure,
|
|
25
25
|
logger: Logger
|
|
26
26
|
) {
|
|
27
|
-
this.logger = logger.child({ service: '
|
|
27
|
+
this.logger = logger.child({ service: 'Sp00kySync:SyncEngine' });
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/**
|
|
@@ -32,7 +32,9 @@ export class SyncEngine {
|
|
|
32
32
|
* Main entry point for sync operations.
|
|
33
33
|
* Uses batch processing to minimize events emitted.
|
|
34
34
|
*/
|
|
35
|
-
async syncRecords(
|
|
35
|
+
async syncRecords(
|
|
36
|
+
diff: RecordVersionDiff
|
|
37
|
+
): Promise<{ remoteFetchMs: number; stillRemoteIds: string[] }> {
|
|
36
38
|
const { added, updated, removed } = diff;
|
|
37
39
|
|
|
38
40
|
this.logger.debug(
|
|
@@ -40,55 +42,70 @@ export class SyncEngine {
|
|
|
40
42
|
added,
|
|
41
43
|
updated,
|
|
42
44
|
removed,
|
|
43
|
-
Category: '
|
|
45
|
+
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
44
46
|
},
|
|
45
47
|
'SyncEngine.syncRecords diff'
|
|
46
48
|
);
|
|
47
49
|
|
|
48
|
-
// Handle removed records: verify they don't exist remotely before deleting
|
|
50
|
+
// Handle removed records: verify they don't exist remotely before deleting
|
|
51
|
+
// locally. Returns ids that LEFT the view's list_ref but still exist upstream
|
|
52
|
+
// (so they weren't deleted) — the caller converges localArray to drop them.
|
|
53
|
+
let stillRemoteIds: string[] = [];
|
|
49
54
|
if (removed.length > 0) {
|
|
50
|
-
await this.handleRemovedRecords(removed);
|
|
55
|
+
stillRemoteIds = await this.handleRemovedRecords(removed);
|
|
51
56
|
}
|
|
52
57
|
|
|
53
58
|
// Fetch added/updated records from remote
|
|
54
59
|
const toFetch = [...added, ...updated];
|
|
55
60
|
const idsToFetch = toFetch.map((x) => x.id);
|
|
56
61
|
if (idsToFetch.length === 0) {
|
|
57
|
-
return;
|
|
62
|
+
return { remoteFetchMs: 0, stillRemoteIds };
|
|
58
63
|
}
|
|
59
64
|
|
|
65
|
+
// Build a version map from the diff (versions come from _00_list_ref)
|
|
66
|
+
const versionMap = new Map<string, number>();
|
|
67
|
+
for (const item of toFetch) {
|
|
68
|
+
versionMap.set(encodeRecordId(item.id), item.version);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Fetch records from remote — avoid SELECT *, <subquery> FROM $param
|
|
72
|
+
// pattern which drops the * fields in SurrealDB v3 (known bug).
|
|
73
|
+
// Versions are already known from the diff's list_ref data.
|
|
74
|
+
const remoteFetchStart = performance.now();
|
|
60
75
|
const [remoteResults] = await this.remote.query<[RecordWithId[]]>(
|
|
61
|
-
|
|
76
|
+
'SELECT * FROM $idsToFetch',
|
|
62
77
|
{ idsToFetch }
|
|
63
78
|
);
|
|
64
|
-
|
|
79
|
+
const remoteFetchMs = performance.now() - remoteFetchStart;
|
|
80
|
+
|
|
65
81
|
// Prepare batch for cache (which handles both DB and DBSP)
|
|
66
82
|
const cacheBatch: CacheRecord[] = [];
|
|
67
83
|
|
|
68
|
-
for (const
|
|
84
|
+
for (const record of remoteResults) {
|
|
69
85
|
if (!record?.id) {
|
|
70
86
|
this.logger.warn(
|
|
71
87
|
{
|
|
72
88
|
record,
|
|
73
89
|
idsToFetch,
|
|
74
|
-
Category: '
|
|
90
|
+
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
75
91
|
},
|
|
76
|
-
'Remote record has no id. Skipping record'
|
|
92
|
+
'Remote record has no id (possibly deleted). Skipping record'
|
|
77
93
|
);
|
|
78
94
|
continue;
|
|
79
95
|
}
|
|
80
96
|
const fullId = encodeRecordId(record.id);
|
|
81
97
|
const table = record.id.table.toString();
|
|
82
98
|
const isAdded = added.some((item) => encodeRecordId(item.id) === fullId);
|
|
99
|
+
const version = versionMap.get(fullId) ?? 0;
|
|
83
100
|
|
|
84
101
|
const localVersion = this.cache.lookup(fullId);
|
|
85
|
-
if (localVersion &&
|
|
102
|
+
if (localVersion && version <= localVersion) {
|
|
86
103
|
this.logger.info(
|
|
87
104
|
{
|
|
88
105
|
recordId: fullId,
|
|
89
|
-
version
|
|
106
|
+
version,
|
|
90
107
|
localVersion,
|
|
91
|
-
Category: '
|
|
108
|
+
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
92
109
|
},
|
|
93
110
|
'Local version is higher than remote version. Skipping record'
|
|
94
111
|
);
|
|
@@ -103,7 +120,7 @@ export class SyncEngine {
|
|
|
103
120
|
table,
|
|
104
121
|
op: isAdded ? 'CREATE' : 'UPDATE',
|
|
105
122
|
record: cleanedRecord as RecordWithId,
|
|
106
|
-
version
|
|
123
|
+
version,
|
|
107
124
|
});
|
|
108
125
|
}
|
|
109
126
|
|
|
@@ -115,49 +132,96 @@ export class SyncEngine {
|
|
|
115
132
|
this.events.emit(SyncEventTypes.RemoteDataIngested, {
|
|
116
133
|
records: remoteResults,
|
|
117
134
|
});
|
|
135
|
+
|
|
136
|
+
return { remoteFetchMs, stillRemoteIds };
|
|
118
137
|
}
|
|
119
138
|
|
|
120
139
|
/**
|
|
121
140
|
* Handle records that exist locally but not in remote array.
|
|
141
|
+
*
|
|
142
|
+
* "Removed" here is a derived signal: the SSP's `_00_list_ref` array no
|
|
143
|
+
* longer references a record that exists locally. That can mean the row
|
|
144
|
+
* was genuinely deleted upstream — but it can also be a benign race
|
|
145
|
+
* (e.g. a record we just created hasn't propagated into the SSP's
|
|
146
|
+
* incantation list yet). Before deleting locally we verify against
|
|
147
|
+
* upstream SurrealDB: if the row still exists there, skip the delete.
|
|
148
|
+
*
|
|
149
|
+
* On verification failure we skip deletion too. Losing a stale local
|
|
150
|
+
* row to a later sync round is recoverable; deleting a fresh row that
|
|
151
|
+
* upstream still has is not.
|
|
122
152
|
*/
|
|
123
|
-
private async handleRemovedRecords(removed: RecordId[]): Promise<
|
|
153
|
+
private async handleRemovedRecords(removed: RecordId[]): Promise<string[]> {
|
|
124
154
|
this.logger.debug(
|
|
125
155
|
{
|
|
126
156
|
removed: removed.map((r) => r.toString()),
|
|
127
|
-
Category: '
|
|
157
|
+
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
128
158
|
},
|
|
129
159
|
'Checking removed records'
|
|
130
160
|
);
|
|
131
161
|
|
|
132
|
-
|
|
162
|
+
// Confirm which of the "removed" ids still exist remotely by selecting the
|
|
163
|
+
// records directly from the id array (the records ARE the FROM target).
|
|
164
|
+
//
|
|
165
|
+
// The exact query form matters on SurrealDB v3.x:
|
|
166
|
+
// - `WHERE id IN $ids` is broken: record-id `IN` matches nothing, so every
|
|
167
|
+
// removed id looked gone and live local records got deleted (a fresh
|
|
168
|
+
// collection vanished mid-session). Do NOT use `IN`.
|
|
169
|
+
// - `SELECT id FROM $ids` — a FIELD projection over a record-id ARRAY —
|
|
170
|
+
// errors "Specify a database to use" on the deployed engine. The catch
|
|
171
|
+
// below then swallowed it and skipped EVERY deletion, so nothing could be
|
|
172
|
+
// deleted anywhere (games, comments, …). Do NOT project a field over the
|
|
173
|
+
// array. (`SELECT * FROM $ids` works but pulls full records — wasteful.)
|
|
174
|
+
// - `SELECT VALUE id FROM $ids` works: a flat array of ids with a NONE entry
|
|
175
|
+
// for each id that no longer exists. We filter the NONE entries out; the
|
|
176
|
+
// survivors are the ids still present upstream.
|
|
177
|
+
let existingRemoteIds: Set<string>;
|
|
133
178
|
try {
|
|
134
|
-
const [
|
|
135
|
-
ids
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
{ Category: 'spooky-client::SyncEngine::handleRemovedRecords' },
|
|
143
|
-
'Remote existence check failed, proceeding with deletion'
|
|
179
|
+
const [existing] = await this.remote.query<[(RecordId | null | undefined)[]]>(
|
|
180
|
+
'SELECT VALUE id FROM $ids',
|
|
181
|
+
{ ids: removed }
|
|
182
|
+
);
|
|
183
|
+
existingRemoteIds = new Set(
|
|
184
|
+
(existing ?? [])
|
|
185
|
+
.filter((id): id is RecordId => id != null)
|
|
186
|
+
.map((id) => encodeRecordId(id))
|
|
144
187
|
);
|
|
188
|
+
} catch (err) {
|
|
189
|
+
// Verification failed. Skip deletion entirely — the next sync
|
|
190
|
+
// round re-derives the diff and we get another shot. The
|
|
191
|
+
// alternative (delete on uncertainty) destroys freshly-created
|
|
192
|
+
// rows when the SSP hasn't yet refreshed `_00_list_ref`.
|
|
193
|
+
this.logger.warn(
|
|
194
|
+
{
|
|
195
|
+
err,
|
|
196
|
+
removed: removed.map((r) => r.toString()),
|
|
197
|
+
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
198
|
+
},
|
|
199
|
+
'Remote existence check failed, skipping deletion to avoid clobbering fresh data'
|
|
200
|
+
);
|
|
201
|
+
return [];
|
|
145
202
|
}
|
|
146
203
|
|
|
204
|
+
// Ids that left the view's list_ref but STILL exist upstream — not deletions,
|
|
205
|
+
// just a view-membership change (e.g. a record whose field changed so it no
|
|
206
|
+
// longer matches the query). The caller drops these from `localArray` so the
|
|
207
|
+
// poll's diff stops re-flagging them every tick (the `job:` churn).
|
|
208
|
+
const stillRemoteIds: string[] = [];
|
|
147
209
|
for (const recordId of removed) {
|
|
148
210
|
const recordIdStr = encodeRecordId(recordId);
|
|
149
211
|
if (!existingRemoteIds.has(recordIdStr)) {
|
|
150
212
|
this.logger.debug(
|
|
151
213
|
{
|
|
152
214
|
recordId: recordIdStr,
|
|
153
|
-
Category: '
|
|
215
|
+
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
154
216
|
},
|
|
155
217
|
'Deleting confirmed removed record'
|
|
156
218
|
);
|
|
157
|
-
|
|
158
219
|
// Use CacheModule to handle both local DB and DBSP deletion
|
|
159
220
|
await this.cache.delete(recordId.table.name, recordIdStr);
|
|
221
|
+
} else {
|
|
222
|
+
stillRemoteIds.push(recordIdStr);
|
|
160
223
|
}
|
|
161
224
|
}
|
|
225
|
+
return stillRemoteIds;
|
|
162
226
|
}
|
|
163
227
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import type { EventDefinition, EventSystem } from '../../../events/index';
|
|
2
|
+
import { createEventSystem } from '../../../events/index';
|
|
3
|
+
import type { RecordVersionArray, SyncHealth } from '../../../types';
|
|
3
4
|
|
|
4
5
|
export const SyncQueueEventTypes = {
|
|
5
6
|
MutationEnqueued: 'MUTATION_ENQUEUED',
|
|
@@ -36,6 +37,7 @@ export const SyncEventTypes = {
|
|
|
36
37
|
QueryUpdated: 'SYNC_QUERY_UPDATED',
|
|
37
38
|
RemoteDataIngested: 'SYNC_REMOTE_DATA_INGESTED',
|
|
38
39
|
MutationRolledBack: 'SYNC_MUTATION_ROLLED_BACK',
|
|
40
|
+
SyncHealthChanged: 'SYNC_HEALTH_CHANGED',
|
|
39
41
|
} as const;
|
|
40
42
|
|
|
41
43
|
export type SyncEventTypeMap = {
|
|
@@ -64,6 +66,10 @@ export type SyncEventTypeMap = {
|
|
|
64
66
|
error: string;
|
|
65
67
|
}
|
|
66
68
|
>;
|
|
69
|
+
[SyncEventTypes.SyncHealthChanged]: EventDefinition<
|
|
70
|
+
typeof SyncEventTypes.SyncHealthChanged,
|
|
71
|
+
SyncHealth
|
|
72
|
+
>;
|
|
67
73
|
};
|
|
68
74
|
|
|
69
75
|
export type SyncEventSystem = EventSystem<SyncEventTypeMap>;
|
|
@@ -73,5 +79,6 @@ export function createSyncEventSystem(): SyncEventSystem {
|
|
|
73
79
|
SyncEventTypes.QueryUpdated,
|
|
74
80
|
SyncEventTypes.RemoteDataIngested,
|
|
75
81
|
SyncEventTypes.MutationRolledBack,
|
|
82
|
+
SyncEventTypes.SyncHealthChanged,
|
|
76
83
|
]);
|
|
77
84
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { DownQueue } from './queue-down';
|
|
3
|
+
import type { DownEvent } from './queue-down';
|
|
4
|
+
import type { LocalStore } from '../../../services/database/index';
|
|
5
|
+
|
|
6
|
+
const silentLogger = {
|
|
7
|
+
child: () => silentLogger,
|
|
8
|
+
debug: () => {},
|
|
9
|
+
info: () => {},
|
|
10
|
+
warn: () => {},
|
|
11
|
+
error: () => {},
|
|
12
|
+
} as any;
|
|
13
|
+
|
|
14
|
+
const register = (hash: string) => ({ type: 'register', payload: { hash } }) as DownEvent;
|
|
15
|
+
|
|
16
|
+
const hashOf = (e: DownEvent) => e.payload.hash;
|
|
17
|
+
|
|
18
|
+
function makeQueue() {
|
|
19
|
+
return new DownQueue({} as LocalStore, silentLogger);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('DownQueue.next failure handling', () => {
|
|
23
|
+
it('re-heads a failing event so a transient failure keeps its order', async () => {
|
|
24
|
+
const q = makeQueue();
|
|
25
|
+
q.push(register('a'));
|
|
26
|
+
q.push(register('b'));
|
|
27
|
+
|
|
28
|
+
const seen: string[] = [];
|
|
29
|
+
await expect(
|
|
30
|
+
q.next(async (e) => {
|
|
31
|
+
seen.push(hashOf(e));
|
|
32
|
+
throw new Error('503');
|
|
33
|
+
})
|
|
34
|
+
).rejects.toThrow('503');
|
|
35
|
+
|
|
36
|
+
expect(seen).toEqual(['a']);
|
|
37
|
+
// 'a' is back at the head, ahead of 'b'.
|
|
38
|
+
await expect(q.next(async (e) => { seen.push(hashOf(e)); throw new Error('503'); })).rejects.toThrow();
|
|
39
|
+
expect(seen).toEqual(['a', 'a']);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('rotates a persistently failing event to the back so others can proceed', async () => {
|
|
43
|
+
const q = makeQueue();
|
|
44
|
+
q.push(register('poison'));
|
|
45
|
+
q.push(register('healthy'));
|
|
46
|
+
|
|
47
|
+
const seen: string[] = [];
|
|
48
|
+
const failPoison = async (e: DownEvent) => {
|
|
49
|
+
seen.push(hashOf(e));
|
|
50
|
+
if (hashOf(e) === 'poison') throw new Error('400 rejected');
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Three attempts keep the head; the third rotates it behind 'healthy'.
|
|
54
|
+
for (let i = 0; i < 3; i++) {
|
|
55
|
+
await expect(q.next(failPoison)).rejects.toThrow();
|
|
56
|
+
}
|
|
57
|
+
expect(seen).toEqual(['poison', 'poison', 'poison']);
|
|
58
|
+
|
|
59
|
+
// 'healthy' is no longer starved.
|
|
60
|
+
await q.next(failPoison);
|
|
61
|
+
expect(seen).toEqual(['poison', 'poison', 'poison', 'healthy']);
|
|
62
|
+
expect(q.size).toBe(1); // only the poison event remains
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('does not rotate when nothing else is waiting', async () => {
|
|
66
|
+
const q = makeQueue();
|
|
67
|
+
q.push(register('only'));
|
|
68
|
+
|
|
69
|
+
for (let i = 0; i < 5; i++) {
|
|
70
|
+
await expect(
|
|
71
|
+
q.next(async () => {
|
|
72
|
+
throw new Error('boom');
|
|
73
|
+
})
|
|
74
|
+
).rejects.toThrow();
|
|
75
|
+
}
|
|
76
|
+
expect(q.size).toBe(1);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('clears the failure count once an event succeeds', async () => {
|
|
80
|
+
const q = makeQueue();
|
|
81
|
+
const event = register('a');
|
|
82
|
+
q.push(event);
|
|
83
|
+
q.push(register('b'));
|
|
84
|
+
|
|
85
|
+
await expect(
|
|
86
|
+
q.next(async () => {
|
|
87
|
+
throw new Error('boom');
|
|
88
|
+
})
|
|
89
|
+
).rejects.toThrow();
|
|
90
|
+
// Succeeds on the retry, so its streak resets rather than carrying over.
|
|
91
|
+
await q.next(async () => {});
|
|
92
|
+
expect(q.size).toBe(1);
|
|
93
|
+
|
|
94
|
+
q.push(event);
|
|
95
|
+
// A fresh streak: it keeps the head again rather than rotating immediately.
|
|
96
|
+
await expect(
|
|
97
|
+
q.next(async () => {
|
|
98
|
+
throw new Error('boom');
|
|
99
|
+
})
|
|
100
|
+
).rejects.toThrow();
|
|
101
|
+
const drained: string[] = [];
|
|
102
|
+
await q.next(async (e) => {
|
|
103
|
+
drained.push(hashOf(e));
|
|
104
|
+
});
|
|
105
|
+
expect(drained).toEqual(['b']);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { LocalStore } from '../../../services/database/index';
|
|
2
|
+
import type {
|
|
3
|
+
SyncQueueEventSystem} from '../events/index';
|
|
2
4
|
import {
|
|
3
5
|
createSyncQueueEventSystem,
|
|
4
|
-
SyncQueueEventSystem,
|
|
5
6
|
SyncQueueEventTypes,
|
|
6
7
|
} from '../events/index';
|
|
7
|
-
import { Logger } from '../../../services/logger/index';
|
|
8
|
+
import type { Logger } from '../../../services/logger/index';
|
|
8
9
|
|
|
9
10
|
export type RegisterEvent = {
|
|
10
11
|
type: 'register';
|
|
@@ -36,17 +37,28 @@ export type CleanupEvent = {
|
|
|
36
37
|
|
|
37
38
|
export type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
|
|
38
39
|
|
|
40
|
+
/**
|
|
41
|
+
* How many times a failing event keeps its place at the head before it is
|
|
42
|
+
* rotated to the back. A transient failure (the SSP still bootstrapping) clears
|
|
43
|
+
* well inside this, so ordering is preserved for the common case; a permanently
|
|
44
|
+
* rejected event (a permission the SSP refuses to lower) stops holding every
|
|
45
|
+
* other query hostage behind it.
|
|
46
|
+
*/
|
|
47
|
+
const MAX_HEAD_RETRIES = 3;
|
|
48
|
+
|
|
39
49
|
export class DownQueue {
|
|
40
50
|
private queue: DownEvent[] = [];
|
|
41
51
|
private _events: SyncQueueEventSystem;
|
|
42
52
|
private logger: Logger;
|
|
53
|
+
/** Consecutive failures per queued event; cleared when it finally succeeds. */
|
|
54
|
+
private failures = new WeakMap<DownEvent, number>();
|
|
43
55
|
|
|
44
56
|
get events(): SyncQueueEventSystem {
|
|
45
57
|
return this._events;
|
|
46
58
|
}
|
|
47
59
|
|
|
48
60
|
constructor(
|
|
49
|
-
private local:
|
|
61
|
+
private local: LocalStore,
|
|
50
62
|
logger: Logger
|
|
51
63
|
) {
|
|
52
64
|
this._events = createSyncQueueEventSystem();
|
|
@@ -71,17 +83,34 @@ export class DownQueue {
|
|
|
71
83
|
});
|
|
72
84
|
}
|
|
73
85
|
|
|
86
|
+
/** Drop all queued events (bucket switch: old-bucket register/sync work is
|
|
87
|
+
* re-derived after the switch; replaying it would target dead query rows). */
|
|
88
|
+
clear(): void {
|
|
89
|
+
this.queue = [];
|
|
90
|
+
}
|
|
91
|
+
|
|
74
92
|
async next(fn: (event: DownEvent) => Promise<void>): Promise<void> {
|
|
75
93
|
const event = this.queue.shift();
|
|
76
94
|
if (event) {
|
|
77
95
|
try {
|
|
78
96
|
await fn(event);
|
|
97
|
+
this.failures.delete(event);
|
|
79
98
|
} catch (error) {
|
|
99
|
+
const attempts = (this.failures.get(event) ?? 0) + 1;
|
|
100
|
+
this.failures.set(event, attempts);
|
|
101
|
+
// Re-head so a transient failure keeps its ordering, but give up the
|
|
102
|
+
// head once it looks permanent and there is other work waiting — one
|
|
103
|
+
// unregisterable query must not stall every other query's registration.
|
|
104
|
+
const starvingOthers = attempts >= MAX_HEAD_RETRIES && this.queue.length > 0;
|
|
105
|
+
if (starvingOthers) {
|
|
106
|
+
this.queue.push(event);
|
|
107
|
+
} else {
|
|
108
|
+
this.queue.unshift(event);
|
|
109
|
+
}
|
|
80
110
|
this.logger.error(
|
|
81
|
-
{ error, event, Category: '
|
|
111
|
+
{ error, event, attempts, rotated: starvingOthers, Category: 'sp00ky-client::DownQueue::next' },
|
|
82
112
|
'Failed to process query'
|
|
83
113
|
);
|
|
84
|
-
this.queue.unshift(event);
|
|
85
114
|
throw error;
|
|
86
115
|
}
|
|
87
116
|
}
|