@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.2
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 -21
- package/README.md +59 -16
- package/dist/index.d.ts +2096 -929
- package/dist/index.js +18217 -5019
- 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/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 +1968 -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 +34 -8
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +173 -0
- package/skills/sp00ky-core/SKILL.md +42 -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 +352 -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 +437 -0
- package/src/client/sp00ky-client.test.ts +428 -0
- package/src/client/sp00ky-client.ts +737 -0
- package/src/index.ts +78 -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 +171 -0
- package/src/kernel/events.ts +60 -0
- package/src/kernel/interpreter.test.ts +116 -0
- package/src/kernel/interpreter.ts +148 -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/index.ts +1153 -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 +168 -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 +200 -0
- package/src/query/materialize.saga.ts +102 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +57 -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 +369 -0
- package/src/query/register.saga.ts +293 -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 +209 -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 +33 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/index.ts +7 -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/sqlite-cache-engine.test.ts +628 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1401 -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 +229 -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 +36 -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 +568 -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 +64 -4
- package/vitest.config.ts +48 -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,75 +1,311 @@
|
|
|
1
1
|
import type { Diagnostic} from 'surrealdb';
|
|
2
|
+
import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
|
|
2
3
|
import { applyDiagnostics, DateTime, RecordId, Surreal } from 'surrealdb';
|
|
3
|
-
import {
|
|
4
|
-
import type { Sp00kyConfig } from '../../types';
|
|
4
|
+
import type { LocalWorkers, Sp00kyConfig } from '../../types';
|
|
5
5
|
import type { Logger } from '../logger/index';
|
|
6
6
|
import { AbstractDatabaseService } from './database';
|
|
7
7
|
import { createDatabaseEventSystem, DatabaseEventTypes } from './events/index';
|
|
8
8
|
import { encodeRecordId } from '../../utils/index';
|
|
9
|
+
import { ANON_USER_ID } from '../../modules/ref-tables';
|
|
10
|
+
import type { SealedQuery } from '../../utils/surql';
|
|
11
|
+
|
|
12
|
+
/** Thrown when a query carries an `epoch` from before a bucket switch. The
|
|
13
|
+
* caller's chain read from the previous user's store; its write must be
|
|
14
|
+
* dropped, not applied to the new bucket. */
|
|
15
|
+
export class StaleEpochError extends Error {
|
|
16
|
+
constructor() {
|
|
17
|
+
super('Local store epoch changed (bucket switch); stale write dropped');
|
|
18
|
+
this.name = 'StaleEpochError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Store URL for a local bucket. One IndexedDB store per user (`anon` for
|
|
23
|
+
* signed-out) so cached rows never leak across accounts on a shared device. */
|
|
24
|
+
export function bucketStoreUrl(bucketId: string): string {
|
|
25
|
+
return `indxdb://${bucketStoreName(bucketId)}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The IndexedDB database name SurrealDB-WASM derives from the store URL. */
|
|
29
|
+
export function bucketStoreName(bucketId: string): string {
|
|
30
|
+
return `sp00ky-${bucketId}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Shared codec: mirrors SurrealDB RecordId/DateTime into our own encodings. */
|
|
34
|
+
const localCodecOptions = {
|
|
35
|
+
valueDecodeVisitor(value: unknown) {
|
|
36
|
+
if (value instanceof RecordId) {
|
|
37
|
+
return encodeRecordId(value);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (value instanceof DateTime) {
|
|
41
|
+
return value.toDate();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return value;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Engine-less Surreal client used as the constructor placeholder. Building this
|
|
50
|
+
* pulls in NO `@surrealdb/wasm` — the ~6 MB wasm engine is deferred to
|
|
51
|
+
* {@link createLocalSurrealClient}, which runs lazily in `connect`/`switchStore`.
|
|
52
|
+
* `connect()` replaces `this.client` with an engine-backed client before any
|
|
53
|
+
* query runs, so this bare client is never actually opened against a store.
|
|
54
|
+
*/
|
|
55
|
+
function createBareSurrealClient(): Surreal {
|
|
56
|
+
return new Surreal({ codecOptions: localCodecOptions });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Engine-backed client. Dynamically imports `@surrealdb/wasm` so the wasm engine
|
|
61
|
+
* only enters the graph as a separate chunk fetched on first connect (module-
|
|
62
|
+
* cached thereafter — `switchStore`'s await is instant).
|
|
63
|
+
*/
|
|
64
|
+
async function createLocalSurrealClient(
|
|
65
|
+
logger: Logger,
|
|
66
|
+
createWorker: LocalWorkers['surreal']
|
|
67
|
+
): Promise<Surreal> {
|
|
68
|
+
const { createWasmWorkerEngines } = await import('@surrealdb/wasm');
|
|
69
|
+
return new Surreal({
|
|
70
|
+
codecOptions: localCodecOptions,
|
|
71
|
+
engines: applyDiagnostics(
|
|
72
|
+
// An app-supplied worker (`database.workers.surreal`) for bundlers that
|
|
73
|
+
// do not bundle the engine's own `new Worker(new URL(...))`.
|
|
74
|
+
createWasmWorkerEngines(createWorker ? { createWorker } : undefined),
|
|
75
|
+
({ key, type, phase, ...other }: Diagnostic) => {
|
|
76
|
+
if (phase === 'progress' || phase === 'after') {
|
|
77
|
+
logger.trace(
|
|
78
|
+
{
|
|
79
|
+
...other,
|
|
80
|
+
key,
|
|
81
|
+
type,
|
|
82
|
+
phase,
|
|
83
|
+
service: 'surrealdb:local',
|
|
84
|
+
Category: 'sp00ky-client::LocalDatabaseService::diagnostics',
|
|
85
|
+
},
|
|
86
|
+
`Local SurrealDB diagnostics captured ${type}:${phase}`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
9
93
|
|
|
10
94
|
export class LocalDatabaseService extends AbstractDatabaseService {
|
|
11
95
|
private config: Sp00kyConfig<any>['database'];
|
|
12
96
|
protected eventType = DatabaseEventTypes.LocalQuery;
|
|
13
97
|
|
|
98
|
+
/** Bucket currently open. Set by `connect`/`switchStore`. */
|
|
99
|
+
private bucketId: string = ANON_USER_ID;
|
|
100
|
+
/**
|
|
101
|
+
* Monotonic store generation. Bumped on every `switchStore`. Async chains
|
|
102
|
+
* that read from the store, await something remote, and then write back
|
|
103
|
+
* (sync poll, SSP stream updates) capture this at chain start and drop
|
|
104
|
+
* their write when it no longer matches — a stale-epoch write would land
|
|
105
|
+
* another user's data in the new bucket.
|
|
106
|
+
*/
|
|
107
|
+
private storeEpoch = 0;
|
|
108
|
+
/** Gate that `query()`/`execute()` await; closed for the switch window. */
|
|
109
|
+
private gate: Promise<void> = Promise.resolve();
|
|
110
|
+
/** The incoming client while a switch is in flight (for unload cleanup). */
|
|
111
|
+
private pendingSwitchClient: Surreal | null = null;
|
|
112
|
+
/** The open `connect()` started, until it settles. */
|
|
113
|
+
private opening: Promise<void> | null = null;
|
|
114
|
+
|
|
14
115
|
constructor(config: Sp00kyConfig<any>['database'], logger: Logger) {
|
|
15
116
|
const events = createDatabaseEventSystem();
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
valueDecodeVisitor(value) {
|
|
20
|
-
if (value instanceof RecordId) {
|
|
21
|
-
return encodeRecordId(value);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
if (value instanceof DateTime) {
|
|
25
|
-
return value.toDate();
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
return value;
|
|
29
|
-
},
|
|
30
|
-
},
|
|
31
|
-
engines: applyDiagnostics(
|
|
32
|
-
createWasmWorkerEngines(),
|
|
33
|
-
({ key, type, phase, ...other }: Diagnostic) => {
|
|
34
|
-
if (phase === 'progress' || phase === 'after') {
|
|
35
|
-
logger.trace(
|
|
36
|
-
{
|
|
37
|
-
...other,
|
|
38
|
-
key,
|
|
39
|
-
type,
|
|
40
|
-
phase,
|
|
41
|
-
service: 'surrealdb:local',
|
|
42
|
-
Category: 'sp00ky-client::LocalDatabaseService::diagnostics',
|
|
43
|
-
},
|
|
44
|
-
`Local SurrealDB diagnostics captured ${type}:${phase}`
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
),
|
|
49
|
-
}),
|
|
50
|
-
logger,
|
|
51
|
-
events
|
|
52
|
-
);
|
|
117
|
+
// Placeholder client with no wasm engine; `connect()` swaps in the real
|
|
118
|
+
// engine-backed client (built lazily) before any query is issued.
|
|
119
|
+
super(createBareSurrealClient(), logger, events);
|
|
53
120
|
this.config = config;
|
|
121
|
+
this.queryTimeoutMs = Math.max(0, config.localOpTimeoutMs ?? DEFAULT_LOCAL_OP_TIMEOUT_MS);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
protected override timeoutError(query: string): Error {
|
|
125
|
+
return new LocalOpTimeoutError(query.slice(0, 80), this.queryTimeoutMs);
|
|
54
126
|
}
|
|
55
127
|
|
|
56
128
|
getConfig(): Sp00kyConfig<any>['database'] {
|
|
57
129
|
return this.config;
|
|
58
130
|
}
|
|
59
131
|
|
|
60
|
-
|
|
132
|
+
get currentBucketId(): string {
|
|
133
|
+
return this.bucketId;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
get epoch(): number {
|
|
137
|
+
return this.storeEpoch;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Close the query gate for a bucket switch. Every `query()`/`execute()`
|
|
142
|
+
* issued after this waits until the returned release fn runs — so work
|
|
143
|
+
* triggered mid-switch (sibling auth subscribers registering queries)
|
|
144
|
+
* lands on the NEW bucket instead of racing the swap. The migrator uses
|
|
145
|
+
* `queryUngated()` to provision the new bucket while the gate is closed.
|
|
146
|
+
*/
|
|
147
|
+
beginSwitch(): () => void {
|
|
148
|
+
let release!: () => void;
|
|
149
|
+
this.gate = new Promise<void>((resolve) => {
|
|
150
|
+
release = resolve;
|
|
151
|
+
});
|
|
152
|
+
return release;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
override async query<T extends unknown[]>(
|
|
156
|
+
query: string,
|
|
157
|
+
vars?: Record<string, unknown>,
|
|
158
|
+
opts?: { epoch?: number }
|
|
159
|
+
): Promise<T> {
|
|
160
|
+
await this.gate;
|
|
161
|
+
// A write whose async chain started before a bucket switch must not land
|
|
162
|
+
// in the new bucket — that would be another user's data. Callers on such
|
|
163
|
+
// chains pass the epoch they captured at chain start; mismatches throw.
|
|
164
|
+
if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) {
|
|
165
|
+
throw new StaleEpochError();
|
|
166
|
+
}
|
|
167
|
+
return super.query(query, vars);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
override async execute<T>(
|
|
171
|
+
query: SealedQuery<T>,
|
|
172
|
+
vars?: Record<string, unknown>,
|
|
173
|
+
opts?: { epoch?: number }
|
|
174
|
+
): Promise<T> {
|
|
175
|
+
const raw = await this.query<unknown[]>(query.sql, vars, opts);
|
|
176
|
+
return query.extract(raw);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Gate-bypassing query — ONLY for the switch path itself (schema
|
|
180
|
+
* provisioning must run while the gate is closed, or it deadlocks). */
|
|
181
|
+
queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T> {
|
|
182
|
+
return super.query(query, vars);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async connect(bucketId: string = ANON_USER_ID): Promise<void> {
|
|
186
|
+
const opening = this.openBucket(bucketId);
|
|
187
|
+
this.opening = opening;
|
|
188
|
+
try {
|
|
189
|
+
await opening;
|
|
190
|
+
} finally {
|
|
191
|
+
if (this.opening === opening) this.opening = null;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private async openBucket(bucketId: string): Promise<void> {
|
|
61
196
|
const { namespace, database } = this.getConfig();
|
|
62
197
|
const store = this.getConfig().store ?? 'memory';
|
|
63
|
-
|
|
198
|
+
this.bucketId = bucketId;
|
|
199
|
+
const storeUrl = store === 'memory' ? 'mem://' : bucketStoreUrl(bucketId);
|
|
64
200
|
this.logger.info(
|
|
65
201
|
{ namespace, database, storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
66
202
|
'Connecting to local database'
|
|
67
203
|
);
|
|
68
204
|
|
|
69
205
|
this.registerUnloadClose();
|
|
206
|
+
// Build the real engine-backed client lazily here (first `@surrealdb/wasm`
|
|
207
|
+
// load), replacing the constructor's engine-less placeholder before any
|
|
208
|
+
// query runs.
|
|
209
|
+
this.client = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
|
|
210
|
+
await this.openWithRecovery(this.client, storeUrl, namespace, database, bucketId, store);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Switch the local store to another user's bucket. Opens the NEW bucket on a
|
|
215
|
+
* second client first (with the same 3-tier recovery), then atomically swaps
|
|
216
|
+
* `this.client` and closes the old one — a failed open never leaves the
|
|
217
|
+
* service on a dead client. Bumps the store epoch so in-flight old-bucket
|
|
218
|
+
* async chains can detect they're stale.
|
|
219
|
+
*
|
|
220
|
+
* Callers own the drain/rebind choreography (close the gate, quiesce sync +
|
|
221
|
+
* timers BEFORE calling this; re-provision + rebind AFTER). Statements that
|
|
222
|
+
* passed the gate before it closed are let finish before the old client
|
|
223
|
+
* closes: the engine streams results from its worker, and a client closed
|
|
224
|
+
* under a statement leaves that statement pending until its deadline, with
|
|
225
|
+
* every later local statement queued behind it.
|
|
226
|
+
*/
|
|
227
|
+
async switchStore(bucketId: string): Promise<void> {
|
|
228
|
+
// Never overlap the boot open: the switch would close the client `connect`
|
|
229
|
+
// is still opening, and both would provision a store at once.
|
|
230
|
+
if (this.opening) await this.opening.catch(() => {});
|
|
231
|
+
if (bucketId === this.bucketId) return;
|
|
232
|
+
const { namespace, database } = this.getConfig();
|
|
233
|
+
const store = this.getConfig().store ?? 'memory';
|
|
234
|
+
this.storeEpoch++;
|
|
235
|
+
|
|
236
|
+
if (store === 'memory') {
|
|
237
|
+
// mem:// has no per-user persistence; close + reopen the same client
|
|
238
|
+
// yields a fresh empty store, which is exactly the reset we want.
|
|
239
|
+
await this.drainStatements();
|
|
240
|
+
try {
|
|
241
|
+
await this.client.close();
|
|
242
|
+
} catch {
|
|
243
|
+
/* ignore */
|
|
244
|
+
}
|
|
245
|
+
await this.openStore(this.client, 'mem://', namespace, database);
|
|
246
|
+
this.bucketId = bucketId;
|
|
247
|
+
this.logger.info(
|
|
248
|
+
{ bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
|
|
249
|
+
'Reset in-memory local store for bucket switch'
|
|
250
|
+
);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const next = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
|
|
255
|
+
this.pendingSwitchClient = next;
|
|
256
|
+
try {
|
|
257
|
+
await this.openWithRecovery(
|
|
258
|
+
next,
|
|
259
|
+
bucketStoreUrl(bucketId),
|
|
260
|
+
namespace,
|
|
261
|
+
database,
|
|
262
|
+
bucketId,
|
|
263
|
+
store
|
|
264
|
+
);
|
|
265
|
+
} finally {
|
|
266
|
+
this.pendingSwitchClient = null;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
await this.drainStatements();
|
|
270
|
+
const old = this.client;
|
|
271
|
+
this.client = next;
|
|
272
|
+
this.bucketId = bucketId;
|
|
273
|
+
try {
|
|
274
|
+
await old.close();
|
|
275
|
+
} catch {
|
|
276
|
+
/* best-effort — the old store's handle is released on unload regardless */
|
|
277
|
+
}
|
|
278
|
+
this.logger.info(
|
|
279
|
+
{ bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
|
|
280
|
+
'Switched local store bucket'
|
|
281
|
+
);
|
|
282
|
+
}
|
|
70
283
|
|
|
284
|
+
/** See `LocalStore.dropBucket`. A memory store keeps nothing to delete. */
|
|
285
|
+
async dropBucket(bucketId: string): Promise<void> {
|
|
286
|
+
if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
|
|
287
|
+
if ((this.getConfig().store ?? 'memory') === 'memory') return;
|
|
288
|
+
await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Open `storeUrl` on `client` with tiered recovery:
|
|
293
|
+
* tier 1 retries the same store (transient idb-handle races — preserves the
|
|
294
|
+
* cache), tier 2 drops THIS bucket's IndexedDB store and reconnects fresh,
|
|
295
|
+
* tier 3 falls back to `mem://` for the session. Only ever drops the bucket
|
|
296
|
+
* being opened — other users' buckets hold their own caches AND un-pushed
|
|
297
|
+
* mutation outboxes, which must survive another bucket's corruption.
|
|
298
|
+
*/
|
|
299
|
+
private async openWithRecovery(
|
|
300
|
+
client: Surreal,
|
|
301
|
+
storeUrl: string,
|
|
302
|
+
namespace: string,
|
|
303
|
+
database: string,
|
|
304
|
+
bucketId: string,
|
|
305
|
+
store: string
|
|
306
|
+
): Promise<void> {
|
|
71
307
|
try {
|
|
72
|
-
await this.openStore(storeUrl, namespace, database);
|
|
308
|
+
await this.openStore(client, storeUrl, namespace, database);
|
|
73
309
|
this.logger.info(
|
|
74
310
|
{ Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
75
311
|
'Connected to local database'
|
|
@@ -101,13 +337,13 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
101
337
|
// the cache on every reload, making warm loads as slow as cold ones.
|
|
102
338
|
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
103
339
|
try {
|
|
104
|
-
await
|
|
340
|
+
await client.close();
|
|
105
341
|
} catch {
|
|
106
342
|
/* ignore */
|
|
107
343
|
}
|
|
108
344
|
await delay(150 * attempt);
|
|
109
345
|
try {
|
|
110
|
-
await this.openStore(storeUrl, namespace, database);
|
|
346
|
+
await this.openStore(client, storeUrl, namespace, database);
|
|
111
347
|
this.logger.info(
|
|
112
348
|
{ attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
113
349
|
'Connected to local database on retry (cache preserved)'
|
|
@@ -121,18 +357,18 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
121
357
|
}
|
|
122
358
|
}
|
|
123
359
|
|
|
124
|
-
// Tier 2 — the store is genuinely unopenable; drop
|
|
125
|
-
// This loses the cache (re-syncs from the server), so it's
|
|
126
|
-
// before in-memory.
|
|
360
|
+
// Tier 2 — the store is genuinely unopenable; drop THIS bucket and reconnect
|
|
361
|
+
// fresh. This loses the bucket's cache (re-syncs from the server), so it's
|
|
362
|
+
// the last resort before in-memory.
|
|
127
363
|
try {
|
|
128
|
-
await
|
|
364
|
+
await client.close();
|
|
129
365
|
} catch {
|
|
130
366
|
/* ignore — closing a half-open connection is best-effort */
|
|
131
367
|
}
|
|
132
|
-
await dropLocalIndexedDbStores(this.logger);
|
|
368
|
+
await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
|
|
133
369
|
|
|
134
370
|
try {
|
|
135
|
-
await this.openStore(storeUrl, namespace, database);
|
|
371
|
+
await this.openStore(client, storeUrl, namespace, database);
|
|
136
372
|
this.logger.info(
|
|
137
373
|
{ Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
138
374
|
'Reconnected to local database after clearing the corrupt store'
|
|
@@ -146,11 +382,11 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
146
382
|
'Local store still failing after clear; falling back to in-memory'
|
|
147
383
|
);
|
|
148
384
|
try {
|
|
149
|
-
await
|
|
385
|
+
await client.close();
|
|
150
386
|
} catch {
|
|
151
387
|
/* ignore */
|
|
152
388
|
}
|
|
153
|
-
await this.openStore('mem://', namespace, database);
|
|
389
|
+
await this.openStore(client, 'mem://', namespace, database);
|
|
154
390
|
this.logger.warn(
|
|
155
391
|
{ Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
156
392
|
'Connected to local database (in-memory fallback)'
|
|
@@ -169,6 +405,7 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
169
405
|
* reload, making warm loads as slow as cold ones. `pagehide` is the reliable
|
|
170
406
|
* unload signal (fires on bfcache + normal navigation); `close()` is async but
|
|
171
407
|
* the WASM worker initiates the IndexedDB connection teardown synchronously.
|
|
408
|
+
* Also closes a mid-switch incoming client so its fresh handle doesn't linger.
|
|
172
409
|
*/
|
|
173
410
|
private registerUnloadClose(): void {
|
|
174
411
|
if (this.unloadCloseRegistered || typeof window === 'undefined') return;
|
|
@@ -179,22 +416,32 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
179
416
|
} catch {
|
|
180
417
|
/* best-effort */
|
|
181
418
|
}
|
|
419
|
+
try {
|
|
420
|
+
void this.pendingSwitchClient?.close();
|
|
421
|
+
} catch {
|
|
422
|
+
/* best-effort */
|
|
423
|
+
}
|
|
182
424
|
};
|
|
183
425
|
window.addEventListener('pagehide', close);
|
|
184
426
|
window.addEventListener('beforeunload', close);
|
|
185
427
|
}
|
|
186
428
|
|
|
187
|
-
private async openStore(
|
|
429
|
+
private async openStore(
|
|
430
|
+
client: Surreal,
|
|
431
|
+
storeUrl: string,
|
|
432
|
+
namespace: string,
|
|
433
|
+
database: string
|
|
434
|
+
): Promise<void> {
|
|
188
435
|
this.logger.debug(
|
|
189
436
|
{ storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
190
437
|
'[LocalDatabaseService] Calling client.connect'
|
|
191
438
|
);
|
|
192
|
-
await
|
|
439
|
+
await client.connect(storeUrl, {});
|
|
193
440
|
this.logger.debug(
|
|
194
441
|
{ namespace, database, Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
195
442
|
'[LocalDatabaseService] client.connect returned. Calling client.use'
|
|
196
443
|
);
|
|
197
|
-
await
|
|
444
|
+
await client.use({ namespace, database });
|
|
198
445
|
this.logger.debug(
|
|
199
446
|
{ Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
200
447
|
'[LocalDatabaseService] client.use returned'
|
|
@@ -218,34 +465,25 @@ export function isLocalStoreOpenError(err: unknown): boolean {
|
|
|
218
465
|
);
|
|
219
466
|
}
|
|
220
467
|
|
|
221
|
-
/** Best-effort delete of
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
*
|
|
225
|
-
|
|
468
|
+
/** Best-effort delete of ONE bucket's IndexedDB store(s). SurrealDB-WASM backs
|
|
469
|
+
* `indxdb://<name>` with one or more IndexedDB databases whose names include
|
|
470
|
+
* `<name>`. Scoped to the given store name — never wipe by the bare `sp00ky`
|
|
471
|
+
* substring, that would take every user's bucket (and their un-pushed mutation
|
|
472
|
+
* outboxes) down with one corrupt store. Resolves even on error/blocked so
|
|
473
|
+
* startup can proceed. No-op outside a browser. Exported for unit tests. */
|
|
474
|
+
export async function dropLocalIndexedDbStores(logger: Logger, storeName: string): Promise<void> {
|
|
226
475
|
if (typeof indexedDB === 'undefined') return;
|
|
227
|
-
const remove = (name: string): Promise<void> =>
|
|
228
|
-
new Promise((resolve) => {
|
|
229
|
-
try {
|
|
230
|
-
const req = indexedDB.deleteDatabase(name);
|
|
231
|
-
req.onsuccess = () => resolve();
|
|
232
|
-
req.onerror = () => resolve();
|
|
233
|
-
req.onblocked = () => resolve();
|
|
234
|
-
} catch {
|
|
235
|
-
resolve();
|
|
236
|
-
}
|
|
237
|
-
});
|
|
238
476
|
try {
|
|
239
477
|
let names: string[] = [];
|
|
240
478
|
if (typeof indexedDB.databases === 'function') {
|
|
241
479
|
const dbs = await indexedDB.databases();
|
|
242
480
|
names = dbs
|
|
243
481
|
.map((d) => d.name)
|
|
244
|
-
.filter((n): n is string => !!n && n
|
|
482
|
+
.filter((n): n is string => !!n && matchesBucketStore(n, storeName));
|
|
245
483
|
}
|
|
246
484
|
// Fall back to the known store name if enumeration is unavailable/empty.
|
|
247
|
-
if (names.length === 0) names = [
|
|
248
|
-
await Promise.all(names.map(
|
|
485
|
+
if (names.length === 0) names = [storeName];
|
|
486
|
+
await Promise.all(names.map(deleteIndexedDb));
|
|
249
487
|
logger.info(
|
|
250
488
|
{ names, Category: 'sp00ky-client::LocalDatabaseService::connect' },
|
|
251
489
|
'Cleared local IndexedDB store(s)'
|
|
@@ -257,3 +495,55 @@ async function dropLocalIndexedDbStores(logger: Logger): Promise<void> {
|
|
|
257
495
|
);
|
|
258
496
|
}
|
|
259
497
|
}
|
|
498
|
+
|
|
499
|
+
/** True when idb database `name` belongs to the bucket store `storeName` —
|
|
500
|
+
* exact match or a derived name (`<storeName>`, `<storeName>-*`, `*<storeName>*`
|
|
501
|
+
* with a non-alphanumeric boundary so `sp00ky-abc` never matches
|
|
502
|
+
* `sp00ky-abcdef`'s store). Exported for unit tests. */
|
|
503
|
+
export function matchesBucketStore(name: string, storeName: string): boolean {
|
|
504
|
+
const lower = name.toLowerCase();
|
|
505
|
+
const target = storeName.toLowerCase();
|
|
506
|
+
const idx = lower.indexOf(target);
|
|
507
|
+
if (idx === -1) return false;
|
|
508
|
+
const after = lower[idx + target.length];
|
|
509
|
+
return after === undefined || !/[a-z0-9_]/.test(after);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Nuke EVERY sp00ky local bucket on this device (manual full reset only —
|
|
513
|
+
* the automated corruption recovery is scoped to one bucket). */
|
|
514
|
+
export async function dropAllSp00kyIndexedDbStores(logger: Logger): Promise<void> {
|
|
515
|
+
if (typeof indexedDB === 'undefined') return;
|
|
516
|
+
try {
|
|
517
|
+
let names: string[] = [];
|
|
518
|
+
if (typeof indexedDB.databases === 'function') {
|
|
519
|
+
const dbs = await indexedDB.databases();
|
|
520
|
+
names = dbs
|
|
521
|
+
.map((d) => d.name)
|
|
522
|
+
.filter((n): n is string => !!n && n.toLowerCase().includes('sp00ky'));
|
|
523
|
+
}
|
|
524
|
+
if (names.length === 0) names = ['sp00ky'];
|
|
525
|
+
await Promise.all(names.map(deleteIndexedDb));
|
|
526
|
+
logger.info(
|
|
527
|
+
{ names, Category: 'sp00ky-client::LocalDatabaseService::reset' },
|
|
528
|
+
'Cleared ALL sp00ky IndexedDB stores'
|
|
529
|
+
);
|
|
530
|
+
} catch (e) {
|
|
531
|
+
logger.warn(
|
|
532
|
+
{ err: e, Category: 'sp00ky-client::LocalDatabaseService::reset' },
|
|
533
|
+
'Failed to enumerate/clear IndexedDB; proceeding anyway'
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function deleteIndexedDb(name: string): Promise<void> {
|
|
539
|
+
return new Promise((resolve) => {
|
|
540
|
+
try {
|
|
541
|
+
const req = indexedDB.deleteDatabase(name);
|
|
542
|
+
req.onsuccess = () => resolve();
|
|
543
|
+
req.onerror = () => resolve();
|
|
544
|
+
req.onblocked = () => resolve();
|
|
545
|
+
} catch {
|
|
546
|
+
resolve();
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
}
|