@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
|
@@ -1,227 +0,0 @@
|
|
|
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
|
-
import { SyncEventTypes, createSyncEventSystem } from './events/index';
|
|
8
|
-
import { encodeRecordId } from '../../utils/index';
|
|
9
|
-
import { cleanRecord } from '../../utils/parser';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* SyncEngine handles the core sync operations: fetching remote records,
|
|
13
|
-
* caching them locally, and ingesting into DBSP.
|
|
14
|
-
*
|
|
15
|
-
* This is extracted from Sp00kySync to separate "how to sync" from "when to sync".
|
|
16
|
-
*/
|
|
17
|
-
export class SyncEngine {
|
|
18
|
-
private logger: Logger;
|
|
19
|
-
public events = createSyncEventSystem();
|
|
20
|
-
|
|
21
|
-
constructor(
|
|
22
|
-
private remote: RemoteDatabaseService,
|
|
23
|
-
private cache: CacheModule,
|
|
24
|
-
private schema: SchemaStructure,
|
|
25
|
-
logger: Logger
|
|
26
|
-
) {
|
|
27
|
-
this.logger = logger.child({ service: 'Sp00kySync:SyncEngine' });
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Sync missing/updated/removed records between local and remote.
|
|
32
|
-
* Main entry point for sync operations.
|
|
33
|
-
* Uses batch processing to minimize events emitted.
|
|
34
|
-
*/
|
|
35
|
-
async syncRecords(
|
|
36
|
-
diff: RecordVersionDiff
|
|
37
|
-
): Promise<{ remoteFetchMs: number; stillRemoteIds: string[] }> {
|
|
38
|
-
const { added, updated, removed } = diff;
|
|
39
|
-
|
|
40
|
-
this.logger.debug(
|
|
41
|
-
{
|
|
42
|
-
added,
|
|
43
|
-
updated,
|
|
44
|
-
removed,
|
|
45
|
-
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
46
|
-
},
|
|
47
|
-
'SyncEngine.syncRecords diff'
|
|
48
|
-
);
|
|
49
|
-
|
|
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[] = [];
|
|
54
|
-
if (removed.length > 0) {
|
|
55
|
-
stillRemoteIds = await this.handleRemovedRecords(removed);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Fetch added/updated records from remote
|
|
59
|
-
const toFetch = [...added, ...updated];
|
|
60
|
-
const idsToFetch = toFetch.map((x) => x.id);
|
|
61
|
-
if (idsToFetch.length === 0) {
|
|
62
|
-
return { remoteFetchMs: 0, stillRemoteIds };
|
|
63
|
-
}
|
|
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();
|
|
75
|
-
const [remoteResults] = await this.remote.query<[RecordWithId[]]>(
|
|
76
|
-
'SELECT * FROM $idsToFetch',
|
|
77
|
-
{ idsToFetch }
|
|
78
|
-
);
|
|
79
|
-
const remoteFetchMs = performance.now() - remoteFetchStart;
|
|
80
|
-
|
|
81
|
-
// Prepare batch for cache (which handles both DB and DBSP)
|
|
82
|
-
const cacheBatch: CacheRecord[] = [];
|
|
83
|
-
|
|
84
|
-
for (const record of remoteResults) {
|
|
85
|
-
if (!record?.id) {
|
|
86
|
-
this.logger.warn(
|
|
87
|
-
{
|
|
88
|
-
record,
|
|
89
|
-
idsToFetch,
|
|
90
|
-
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
91
|
-
},
|
|
92
|
-
'Remote record has no id (possibly deleted). Skipping record'
|
|
93
|
-
);
|
|
94
|
-
continue;
|
|
95
|
-
}
|
|
96
|
-
const fullId = encodeRecordId(record.id);
|
|
97
|
-
const table = record.id.table.toString();
|
|
98
|
-
const isAdded = added.some((item) => encodeRecordId(item.id) === fullId);
|
|
99
|
-
const version = versionMap.get(fullId) ?? 0;
|
|
100
|
-
|
|
101
|
-
const localVersion = this.cache.lookup(fullId);
|
|
102
|
-
if (localVersion && version <= localVersion) {
|
|
103
|
-
this.logger.info(
|
|
104
|
-
{
|
|
105
|
-
recordId: fullId,
|
|
106
|
-
version,
|
|
107
|
-
localVersion,
|
|
108
|
-
Category: 'sp00ky-client::SyncEngine::syncRecords',
|
|
109
|
-
},
|
|
110
|
-
'Local version is higher than remote version. Skipping record'
|
|
111
|
-
);
|
|
112
|
-
continue;
|
|
113
|
-
}
|
|
114
|
-
const tableSchema = this.schema.tables.find((t) => t.name === table);
|
|
115
|
-
const cleanedRecord = tableSchema
|
|
116
|
-
? cleanRecord(tableSchema.columns, record)
|
|
117
|
-
: record;
|
|
118
|
-
|
|
119
|
-
cacheBatch.push({
|
|
120
|
-
table,
|
|
121
|
-
op: isAdded ? 'CREATE' : 'UPDATE',
|
|
122
|
-
record: cleanedRecord as RecordWithId,
|
|
123
|
-
version,
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// Use CacheModule to handle both local DB and DBSP ingestion
|
|
128
|
-
if (cacheBatch.length > 0) {
|
|
129
|
-
await this.cache.saveBatch(cacheBatch);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
this.events.emit(SyncEventTypes.RemoteDataIngested, {
|
|
133
|
-
records: remoteResults,
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
return { remoteFetchMs, stillRemoteIds };
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/**
|
|
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.
|
|
152
|
-
*/
|
|
153
|
-
private async handleRemovedRecords(removed: RecordId[]): Promise<string[]> {
|
|
154
|
-
this.logger.debug(
|
|
155
|
-
{
|
|
156
|
-
removed: removed.map((r) => r.toString()),
|
|
157
|
-
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
158
|
-
},
|
|
159
|
-
'Checking removed records'
|
|
160
|
-
);
|
|
161
|
-
|
|
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>;
|
|
178
|
-
try {
|
|
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))
|
|
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 [];
|
|
202
|
-
}
|
|
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[] = [];
|
|
209
|
-
for (const recordId of removed) {
|
|
210
|
-
const recordIdStr = encodeRecordId(recordId);
|
|
211
|
-
if (!existingRemoteIds.has(recordIdStr)) {
|
|
212
|
-
this.logger.debug(
|
|
213
|
-
{
|
|
214
|
-
recordId: recordIdStr,
|
|
215
|
-
Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
|
|
216
|
-
},
|
|
217
|
-
'Deleting confirmed removed record'
|
|
218
|
-
);
|
|
219
|
-
// Use CacheModule to handle both local DB and DBSP deletion
|
|
220
|
-
await this.cache.delete(recordId.table.name, recordIdStr);
|
|
221
|
-
} else {
|
|
222
|
-
stillRemoteIds.push(recordIdStr);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
return stillRemoteIds;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import type { EventDefinition, EventSystem } from '../../../events/index';
|
|
2
|
-
import { createEventSystem } from '../../../events/index';
|
|
3
|
-
import type { RecordVersionArray, SyncHealth } from '../../../types';
|
|
4
|
-
|
|
5
|
-
export const SyncQueueEventTypes = {
|
|
6
|
-
MutationEnqueued: 'MUTATION_ENQUEUED',
|
|
7
|
-
MutationDequeued: 'MUTATION_DEQUEUED',
|
|
8
|
-
QueryItemEnqueued: 'QUERY_ITEM_ENQUEUED',
|
|
9
|
-
} as const;
|
|
10
|
-
|
|
11
|
-
export type SyncQueueEventTypeMap = {
|
|
12
|
-
[SyncQueueEventTypes.MutationEnqueued]: EventDefinition<
|
|
13
|
-
typeof SyncQueueEventTypes.MutationEnqueued,
|
|
14
|
-
{ queueSize: number }
|
|
15
|
-
>;
|
|
16
|
-
[SyncQueueEventTypes.MutationDequeued]: EventDefinition<
|
|
17
|
-
typeof SyncQueueEventTypes.MutationDequeued,
|
|
18
|
-
{ queueSize: number }
|
|
19
|
-
>;
|
|
20
|
-
[SyncQueueEventTypes.QueryItemEnqueued]: EventDefinition<
|
|
21
|
-
typeof SyncQueueEventTypes.QueryItemEnqueued,
|
|
22
|
-
{ queueSize: number }
|
|
23
|
-
>;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
export type SyncQueueEventSystem = EventSystem<SyncQueueEventTypeMap>;
|
|
27
|
-
|
|
28
|
-
export function createSyncQueueEventSystem(): SyncQueueEventSystem {
|
|
29
|
-
return createEventSystem([
|
|
30
|
-
SyncQueueEventTypes.QueryItemEnqueued,
|
|
31
|
-
SyncQueueEventTypes.MutationEnqueued,
|
|
32
|
-
SyncQueueEventTypes.MutationDequeued,
|
|
33
|
-
]);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export const SyncEventTypes = {
|
|
37
|
-
QueryUpdated: 'SYNC_QUERY_UPDATED',
|
|
38
|
-
RemoteDataIngested: 'SYNC_REMOTE_DATA_INGESTED',
|
|
39
|
-
MutationRolledBack: 'SYNC_MUTATION_ROLLED_BACK',
|
|
40
|
-
SyncHealthChanged: 'SYNC_HEALTH_CHANGED',
|
|
41
|
-
} as const;
|
|
42
|
-
|
|
43
|
-
export type SyncEventTypeMap = {
|
|
44
|
-
[SyncEventTypes.QueryUpdated]: EventDefinition<
|
|
45
|
-
typeof SyncEventTypes.QueryUpdated,
|
|
46
|
-
{
|
|
47
|
-
queryId: any; // RecordId<string> but imported
|
|
48
|
-
localHash?: string;
|
|
49
|
-
localArray?: RecordVersionArray;
|
|
50
|
-
remoteHash?: string;
|
|
51
|
-
remoteArray?: RecordVersionArray;
|
|
52
|
-
records: Record<string, any>[];
|
|
53
|
-
}
|
|
54
|
-
>;
|
|
55
|
-
[SyncEventTypes.RemoteDataIngested]: EventDefinition<
|
|
56
|
-
typeof SyncEventTypes.RemoteDataIngested,
|
|
57
|
-
{
|
|
58
|
-
records: Record<string, any>[];
|
|
59
|
-
}
|
|
60
|
-
>;
|
|
61
|
-
[SyncEventTypes.MutationRolledBack]: EventDefinition<
|
|
62
|
-
typeof SyncEventTypes.MutationRolledBack,
|
|
63
|
-
{
|
|
64
|
-
eventType: string;
|
|
65
|
-
recordId: string;
|
|
66
|
-
error: string;
|
|
67
|
-
}
|
|
68
|
-
>;
|
|
69
|
-
[SyncEventTypes.SyncHealthChanged]: EventDefinition<
|
|
70
|
-
typeof SyncEventTypes.SyncHealthChanged,
|
|
71
|
-
SyncHealth
|
|
72
|
-
>;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
export type SyncEventSystem = EventSystem<SyncEventTypeMap>;
|
|
76
|
-
|
|
77
|
-
export function createSyncEventSystem(): SyncEventSystem {
|
|
78
|
-
return createEventSystem([
|
|
79
|
-
SyncEventTypes.QueryUpdated,
|
|
80
|
-
SyncEventTypes.RemoteDataIngested,
|
|
81
|
-
SyncEventTypes.MutationRolledBack,
|
|
82
|
-
SyncEventTypes.SyncHealthChanged,
|
|
83
|
-
]);
|
|
84
|
-
}
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import type { LocalDatabaseService } from '../../../services/database/index';
|
|
2
|
-
import type {
|
|
3
|
-
SyncQueueEventSystem} from '../events/index';
|
|
4
|
-
import {
|
|
5
|
-
createSyncQueueEventSystem,
|
|
6
|
-
SyncQueueEventTypes,
|
|
7
|
-
} from '../events/index';
|
|
8
|
-
import type { Logger } from '../../../services/logger/index';
|
|
9
|
-
|
|
10
|
-
export type RegisterEvent = {
|
|
11
|
-
type: 'register';
|
|
12
|
-
payload: {
|
|
13
|
-
hash: string;
|
|
14
|
-
};
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
export type SyncEvent = {
|
|
18
|
-
type: 'sync';
|
|
19
|
-
payload: {
|
|
20
|
-
hash: string;
|
|
21
|
-
};
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export type HeartbeatEvent = {
|
|
25
|
-
type: 'heartbeat';
|
|
26
|
-
payload: {
|
|
27
|
-
hash: string;
|
|
28
|
-
};
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
export type CleanupEvent = {
|
|
32
|
-
type: 'cleanup';
|
|
33
|
-
payload: {
|
|
34
|
-
hash: string;
|
|
35
|
-
};
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
export type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
|
|
39
|
-
|
|
40
|
-
export class DownQueue {
|
|
41
|
-
private queue: DownEvent[] = [];
|
|
42
|
-
private _events: SyncQueueEventSystem;
|
|
43
|
-
private logger: Logger;
|
|
44
|
-
|
|
45
|
-
get events(): SyncQueueEventSystem {
|
|
46
|
-
return this._events;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
constructor(
|
|
50
|
-
private local: LocalDatabaseService,
|
|
51
|
-
logger: Logger
|
|
52
|
-
) {
|
|
53
|
-
this._events = createSyncQueueEventSystem();
|
|
54
|
-
this.logger = logger.child({ service: 'DownQueue' });
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
get size(): number {
|
|
58
|
-
return this.queue.length;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
push(event: DownEvent) {
|
|
62
|
-
this.queue.push(event);
|
|
63
|
-
this.emitPushEvent();
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
private emitPushEvent() {
|
|
67
|
-
this._events.addEvent({
|
|
68
|
-
type: SyncQueueEventTypes.QueryItemEnqueued,
|
|
69
|
-
payload: {
|
|
70
|
-
queueSize: this.queue.length,
|
|
71
|
-
},
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async next(fn: (event: DownEvent) => Promise<void>): Promise<void> {
|
|
76
|
-
const event = this.queue.shift();
|
|
77
|
-
if (event) {
|
|
78
|
-
try {
|
|
79
|
-
await fn(event);
|
|
80
|
-
} catch (error) {
|
|
81
|
-
this.logger.error(
|
|
82
|
-
{ error, event, Category: 'sp00ky-client::DownQueue::next' },
|
|
83
|
-
'Failed to process query'
|
|
84
|
-
);
|
|
85
|
-
this.queue.unshift(event);
|
|
86
|
-
throw error;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
}
|
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import type { RecordId } from 'surrealdb';
|
|
2
|
-
import type { LocalDatabaseService } from '../../../services/database/index';
|
|
3
|
-
import type {
|
|
4
|
-
SyncQueueEventSystem} from '../events/index';
|
|
5
|
-
import {
|
|
6
|
-
createSyncQueueEventSystem,
|
|
7
|
-
SyncQueueEventTypes,
|
|
8
|
-
} from '../events/index';
|
|
9
|
-
import { parseRecordIdString, extractTablePart, classifySyncError } from '../../../utils/index';
|
|
10
|
-
import type { Logger } from '../../../services/logger/index';
|
|
11
|
-
import type { PushEventOptions } from '../../../events/index';
|
|
12
|
-
|
|
13
|
-
export type CreateEvent = {
|
|
14
|
-
type: 'create';
|
|
15
|
-
mutation_id: RecordId;
|
|
16
|
-
record_id: RecordId;
|
|
17
|
-
data: Record<string, unknown>;
|
|
18
|
-
record?: Record<string, unknown>;
|
|
19
|
-
tableName?: string;
|
|
20
|
-
options?: PushEventOptions;
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
export type UpdateEvent = {
|
|
24
|
-
type: 'update';
|
|
25
|
-
mutation_id: RecordId;
|
|
26
|
-
record_id: RecordId;
|
|
27
|
-
data: Record<string, unknown>;
|
|
28
|
-
record?: Record<string, unknown>;
|
|
29
|
-
beforeRecord?: Record<string, unknown>;
|
|
30
|
-
options?: PushEventOptions;
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
export type DeleteEvent = {
|
|
34
|
-
type: 'delete';
|
|
35
|
-
mutation_id: RecordId;
|
|
36
|
-
record_id: RecordId;
|
|
37
|
-
options?: PushEventOptions;
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
export type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
|
|
41
|
-
|
|
42
|
-
export type RollbackCallback = (event: UpEvent, error: Error) => Promise<void>;
|
|
43
|
-
|
|
44
|
-
export class UpQueue {
|
|
45
|
-
private queue: UpEvent[] = [];
|
|
46
|
-
private _events: SyncQueueEventSystem;
|
|
47
|
-
private logger: Logger;
|
|
48
|
-
private debouncedMutations: Map<string, { timer: any; firstBeforeRecord?: Record<string, unknown> }>;
|
|
49
|
-
|
|
50
|
-
get events(): SyncQueueEventSystem {
|
|
51
|
-
return this._events;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
constructor(
|
|
55
|
-
private local: LocalDatabaseService,
|
|
56
|
-
logger: Logger
|
|
57
|
-
) {
|
|
58
|
-
this._events = createSyncQueueEventSystem();
|
|
59
|
-
this.logger = logger.child({ service: 'UpQueue' });
|
|
60
|
-
this.debouncedMutations = new Map();
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
get size(): number {
|
|
64
|
-
return this.queue.length;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
push(event: UpEvent) {
|
|
68
|
-
if (event.options?.debounced) {
|
|
69
|
-
const { key, delay } = event.options.debounced;
|
|
70
|
-
this.handleDebouncedMutation(event, key, delay);
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
this.addToQueue(event);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
private addToQueue(event: UpEvent) {
|
|
77
|
-
this.queue.push(event);
|
|
78
|
-
this._events.addEvent({
|
|
79
|
-
type: SyncQueueEventTypes.MutationEnqueued,
|
|
80
|
-
payload: { queueSize: this.queue.length },
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
private handleDebouncedMutation(event: UpEvent, key: string, delay: number) {
|
|
85
|
-
const existing = this.debouncedMutations.get(key);
|
|
86
|
-
let firstBeforeRecord: Record<string, unknown> | undefined;
|
|
87
|
-
|
|
88
|
-
if (existing) {
|
|
89
|
-
clearTimeout(existing.timer);
|
|
90
|
-
// Preserve the beforeRecord from the first event in the debounce sequence
|
|
91
|
-
firstBeforeRecord = existing.firstBeforeRecord;
|
|
92
|
-
} else if (event.type === 'update') {
|
|
93
|
-
firstBeforeRecord = event.beforeRecord;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const timer = setTimeout(() => {
|
|
97
|
-
this.debouncedMutations.delete(key);
|
|
98
|
-
// Attach the first beforeRecord to the final debounced event
|
|
99
|
-
if (firstBeforeRecord && event.type === 'update') {
|
|
100
|
-
event.beforeRecord = firstBeforeRecord;
|
|
101
|
-
}
|
|
102
|
-
this.addToQueue(event);
|
|
103
|
-
}, delay);
|
|
104
|
-
|
|
105
|
-
this.debouncedMutations.set(key, { timer, firstBeforeRecord });
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async next(fn: (event: UpEvent) => Promise<void>, onRollback?: RollbackCallback): Promise<void> {
|
|
109
|
-
const event = this.queue.shift();
|
|
110
|
-
if (event) {
|
|
111
|
-
try {
|
|
112
|
-
await fn(event);
|
|
113
|
-
} catch (error) {
|
|
114
|
-
const errorType = classifySyncError(error);
|
|
115
|
-
|
|
116
|
-
if (errorType === 'network') {
|
|
117
|
-
this.logger.error(
|
|
118
|
-
{ error, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
119
|
-
'Network error processing mutation, re-queuing'
|
|
120
|
-
);
|
|
121
|
-
this.queue.unshift(event);
|
|
122
|
-
throw error;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Application error — rollback instead of re-queuing
|
|
126
|
-
this.logger.error(
|
|
127
|
-
{ error, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
128
|
-
'Application error processing mutation, rolling back'
|
|
129
|
-
);
|
|
130
|
-
try {
|
|
131
|
-
await this.removeEventFromDatabase(event.mutation_id);
|
|
132
|
-
} catch (removeError) {
|
|
133
|
-
this.logger.error(
|
|
134
|
-
{ error: removeError, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
135
|
-
'Failed to remove rolled-back mutation from database'
|
|
136
|
-
);
|
|
137
|
-
}
|
|
138
|
-
if (onRollback) {
|
|
139
|
-
try {
|
|
140
|
-
await onRollback(event, error instanceof Error ? error : new Error(String(error)));
|
|
141
|
-
} catch (rollbackError) {
|
|
142
|
-
this.logger.error(
|
|
143
|
-
{ error: rollbackError, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
144
|
-
'Rollback handler failed'
|
|
145
|
-
);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
this._events.addEvent({
|
|
149
|
-
type: SyncQueueEventTypes.MutationDequeued,
|
|
150
|
-
payload: { queueSize: this.queue.length },
|
|
151
|
-
});
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
try {
|
|
155
|
-
await this.removeEventFromDatabase(event.mutation_id);
|
|
156
|
-
} catch (error) {
|
|
157
|
-
this.logger.error(
|
|
158
|
-
{ error, event, Category: 'sp00ky-client::UpQueue::next' },
|
|
159
|
-
'Failed to remove mutation from database after successful processing'
|
|
160
|
-
);
|
|
161
|
-
}
|
|
162
|
-
this._events.addEvent({
|
|
163
|
-
type: SyncQueueEventTypes.MutationDequeued,
|
|
164
|
-
payload: { queueSize: this.queue.length },
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
async removeEventFromDatabase(mutation_id: RecordId) {
|
|
170
|
-
return this.local.query(`DELETE $mutation_id`, { mutation_id });
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
async loadFromDatabase() {
|
|
174
|
-
try {
|
|
175
|
-
const [records] = await this.local.query<any>(
|
|
176
|
-
`SELECT * FROM _00_pending_mutations ORDER BY created_at ASC`
|
|
177
|
-
);
|
|
178
|
-
|
|
179
|
-
this.queue = records
|
|
180
|
-
.map((r: any): UpEvent | null => {
|
|
181
|
-
switch (r.mutationType) {
|
|
182
|
-
case 'create':
|
|
183
|
-
return {
|
|
184
|
-
type: 'create',
|
|
185
|
-
mutation_id: parseRecordIdString(r.id),
|
|
186
|
-
record_id: parseRecordIdString(r.recordId),
|
|
187
|
-
data: r.data,
|
|
188
|
-
tableName: extractTablePart(r.recordId),
|
|
189
|
-
};
|
|
190
|
-
case 'update':
|
|
191
|
-
return {
|
|
192
|
-
type: 'update',
|
|
193
|
-
mutation_id: parseRecordIdString(r.id),
|
|
194
|
-
record_id: parseRecordIdString(r.recordId),
|
|
195
|
-
data: r.data,
|
|
196
|
-
beforeRecord: r.beforeRecord,
|
|
197
|
-
};
|
|
198
|
-
case 'delete':
|
|
199
|
-
return {
|
|
200
|
-
type: 'delete',
|
|
201
|
-
mutation_id: parseRecordIdString(r.id),
|
|
202
|
-
record_id: parseRecordIdString(r.recordId),
|
|
203
|
-
};
|
|
204
|
-
default:
|
|
205
|
-
this.logger.warn(
|
|
206
|
-
{
|
|
207
|
-
mutationType: r.mutationType,
|
|
208
|
-
record: r,
|
|
209
|
-
Category: 'sp00ky-client::UpQueue::loadFromDatabase',
|
|
210
|
-
},
|
|
211
|
-
'Unknown mutation type'
|
|
212
|
-
);
|
|
213
|
-
return null;
|
|
214
|
-
}
|
|
215
|
-
})
|
|
216
|
-
.filter((e: UpEvent | null): e is UpEvent => e !== null);
|
|
217
|
-
} catch (error) {
|
|
218
|
-
this.logger.error(
|
|
219
|
-
{ error, Category: 'sp00ky-client::UpQueue::loadFromDatabase' },
|
|
220
|
-
'Failed to load pending mutations from database'
|
|
221
|
-
);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|