@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
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test-only doubles for the blob cache. Follows the repo's convention of
|
|
3
|
+
* hand-rolled fakes at the module boundary (cf. `sqlite-transport.fixture.ts`)
|
|
4
|
+
* rather than pulling in a DOM or a fake-indexeddb: `BlobCache` is pure logic
|
|
5
|
+
* over `BlobStore` + `LocalStore`, so both can be faked in node.
|
|
6
|
+
*/
|
|
7
|
+
import { RecordId } from 'surrealdb';
|
|
8
|
+
import type { Id, LocalStore, Row } from '../database/cache-engine';
|
|
9
|
+
|
|
10
|
+
/** A `LocalStore` with only the three verbs `BlobManifest` uses. */
|
|
11
|
+
export interface FakeLocalStore {
|
|
12
|
+
store: LocalStore;
|
|
13
|
+
rows: Map<string, Row>;
|
|
14
|
+
/** Counts, so a test can assert the manifest batched instead of write-storming. */
|
|
15
|
+
upserts: number;
|
|
16
|
+
deletes: number;
|
|
17
|
+
/** Make every read fail — the memory-fallback / wiped-store case. */
|
|
18
|
+
failReads: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function idOf(id: Id): string {
|
|
22
|
+
return id instanceof RecordId ? String(id.id) : String(id);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function fakeLocalStore(): FakeLocalStore {
|
|
26
|
+
const state: FakeLocalStore = {
|
|
27
|
+
rows: new Map(),
|
|
28
|
+
upserts: 0,
|
|
29
|
+
deletes: 0,
|
|
30
|
+
failReads: false,
|
|
31
|
+
store: null as unknown as LocalStore,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
state.store = {
|
|
35
|
+
async selectByIds(_table: string, ids: Id[]): Promise<Row[]> {
|
|
36
|
+
if (state.failReads) throw new Error('local store unavailable');
|
|
37
|
+
const out: Row[] = [];
|
|
38
|
+
for (const id of ids) {
|
|
39
|
+
const key = idOf(id);
|
|
40
|
+
const row = state.rows.get(key);
|
|
41
|
+
if (row) out.push({ ...row, id: new RecordId('_00_blob', key) });
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
},
|
|
45
|
+
async upsert(_table: string, id: Id, data: Row): Promise<void> {
|
|
46
|
+
state.upserts++;
|
|
47
|
+
state.rows.set(idOf(id), { ...data });
|
|
48
|
+
},
|
|
49
|
+
async delete(_table: string, id: Id): Promise<void> {
|
|
50
|
+
state.deletes++;
|
|
51
|
+
state.rows.delete(idOf(id));
|
|
52
|
+
},
|
|
53
|
+
} as unknown as LocalStore;
|
|
54
|
+
|
|
55
|
+
return state;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A logger that satisfies the `Logger` shape without printing. */
|
|
59
|
+
export function silentLogger(): any {
|
|
60
|
+
const noop = () => {};
|
|
61
|
+
const logger: any = { debug: noop, info: noop, warn: noop, error: noop, fatal: noop, trace: noop };
|
|
62
|
+
logger.child = () => logger;
|
|
63
|
+
return logger;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Deterministic object-URL factory: no DOM needed, and revokes are countable. */
|
|
67
|
+
export function fakeUrls() {
|
|
68
|
+
let next = 0;
|
|
69
|
+
const live = new Set<string>();
|
|
70
|
+
const revoked: string[] = [];
|
|
71
|
+
return {
|
|
72
|
+
live,
|
|
73
|
+
revoked,
|
|
74
|
+
factory: {
|
|
75
|
+
create: (_blob: Blob) => {
|
|
76
|
+
const url = `blob:fake/${next++}`;
|
|
77
|
+
live.add(url);
|
|
78
|
+
return url;
|
|
79
|
+
},
|
|
80
|
+
revoke: (url: string) => {
|
|
81
|
+
live.delete(url);
|
|
82
|
+
revoked.push(url);
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function bytes(size: number, fill = 'a'): Blob {
|
|
89
|
+
return new Blob([fill.repeat(size)]);
|
|
90
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Logger } from '../logger/index';
|
|
2
|
+
import type { LocalStore } from '../database/cache-engine';
|
|
3
|
+
import type { BlobCacheOptions } from './blob-cache';
|
|
4
|
+
import { BlobCache } from './blob-cache';
|
|
5
|
+
import { BlobManifest } from './blob-manifest';
|
|
6
|
+
import type { BlobStore } from './blob-store';
|
|
7
|
+
import { MemoryBlobStore, OpfsBlobStore, opfsWritableSupported } from './blob-store';
|
|
8
|
+
|
|
9
|
+
export type { BlobKey, BlobStat, BlobStore } from './blob-store';
|
|
10
|
+
export { BLOB_ROOT_DIR, BlobKeyError, MemoryBlobStore, OpfsBlobStore, blobKeyId, opfsWritableSupported } from './blob-store';
|
|
11
|
+
export type { BlobEntry } from './blob-manifest';
|
|
12
|
+
export { BLOB_TABLE, BlobManifest } from './blob-manifest';
|
|
13
|
+
export type { BlobCacheOptions, BlobCacheStats, BlobReadOptions, BlobUrlLease } from './blob-cache';
|
|
14
|
+
export { BlobCache } from './blob-cache';
|
|
15
|
+
|
|
16
|
+
/** Ceiling on the default budget, before the quota fraction is applied. */
|
|
17
|
+
const MAX_DEFAULT_BUDGET_BYTES = 512 * 1024 * 1024;
|
|
18
|
+
/** Share of the origin quota the blob cache may claim by default. The local
|
|
19
|
+
* database, the SQLite pool and any app storage share the same quota. */
|
|
20
|
+
const QUOTA_FRACTION = 0.25;
|
|
21
|
+
/** Used until `resolveBlobBudget()` reports back, and when there is no
|
|
22
|
+
* `navigator.storage.estimate()` to ask. */
|
|
23
|
+
export const FALLBACK_BLOB_BUDGET_BYTES = 128 * 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Budget from the real origin quota when the browser will tell us, otherwise a
|
|
27
|
+
* conservative constant. Async because `estimate()` is; call it once at init
|
|
28
|
+
* and hand the result to {@link BlobCache.setMaxBytes}.
|
|
29
|
+
*/
|
|
30
|
+
export async function resolveBlobBudget(configured?: number): Promise<number> {
|
|
31
|
+
if (typeof configured === 'number' && configured > 0) return configured;
|
|
32
|
+
try {
|
|
33
|
+
const { quota } = (await navigator.storage.estimate()) ?? {};
|
|
34
|
+
if (typeof quota === 'number' && quota > 0) {
|
|
35
|
+
return Math.min(MAX_DEFAULT_BUDGET_BYTES, Math.floor(quota * QUOTA_FRACTION));
|
|
36
|
+
}
|
|
37
|
+
} catch {
|
|
38
|
+
/* private mode, or no Storage API: fall through */
|
|
39
|
+
}
|
|
40
|
+
return FALLBACK_BLOB_BUDGET_BYTES;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CreateBlobCacheOptions {
|
|
44
|
+
local: LocalStore;
|
|
45
|
+
namespace: string;
|
|
46
|
+
logger: Logger;
|
|
47
|
+
fetchRemote: BlobCacheOptions['fetchRemote'];
|
|
48
|
+
headRemote?: BlobCacheOptions['headRemote'];
|
|
49
|
+
maxBytes?: number;
|
|
50
|
+
/** Force a store instead of feature-detecting. Tests and custom engines. */
|
|
51
|
+
store?: BlobStore;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Build the cache for a client. Falls back to an in-memory store when OPFS
|
|
56
|
+
* cannot be written (Safari before `createWritable`, private modes, non-browser
|
|
57
|
+
* hosts): the cache still dedupes and serves within the tab, which is exactly
|
|
58
|
+
* the behaviour that existed before it — nothing regresses, nothing persists.
|
|
59
|
+
*/
|
|
60
|
+
export function createBlobCache(opts: CreateBlobCacheOptions): BlobCache {
|
|
61
|
+
const store = opts.store ?? (opfsWritableSupported() ? new OpfsBlobStore(opts.namespace) : new MemoryBlobStore(opts.namespace));
|
|
62
|
+
return new BlobCache({
|
|
63
|
+
store,
|
|
64
|
+
manifest: new BlobManifest(opts.local),
|
|
65
|
+
fetchRemote: opts.fetchRemote,
|
|
66
|
+
headRemote: opts.headRemote,
|
|
67
|
+
logger: opts.logger,
|
|
68
|
+
maxBytes: opts.maxBytes ?? FALLBACK_BLOB_BUDGET_BYTES,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import type { QueryPlan, RelationPlan, WhereNode } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { SealedQuery } from '../../utils/surql';
|
|
3
|
+
import type { DatabaseEventSystem } from './events/index';
|
|
4
|
+
import type { Sp00kyConfig, StorageHealth } from '../../types';
|
|
5
|
+
import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-info';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A materialized row. Keys are field names; values are already decoded to the
|
|
9
|
+
* client's runtime shapes (RecordId stays a RecordId, bytes a Uint8Array, …) so
|
|
10
|
+
* every backend hands `DataModule` the same shape SurrealDB does today.
|
|
11
|
+
*/
|
|
12
|
+
export type Row = Record<string, unknown>;
|
|
13
|
+
|
|
14
|
+
/** A record identifier — a `RecordId` or its stable string form (`table:id`). */
|
|
15
|
+
export type Id = unknown;
|
|
16
|
+
|
|
17
|
+
/** How an order clause is expressed everywhere in the engine layer. */
|
|
18
|
+
export type OrderBy = [field: string, direction: 'asc' | 'desc'][];
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Batched relation fetch: "give me every row of `table` whose `matchField` is
|
|
22
|
+
* one of `keys`, filtered by `where`, ordered by `orderBy`". This is the single
|
|
23
|
+
* primitive relation decomposition (§3) leans on — implemented as
|
|
24
|
+
* `SELECT … WHERE <matchField> IN (…)` on SQLite, `SELECT … FROM $keys` /
|
|
25
|
+
* `WHERE <matchField> IN $keys` on SurrealDB, or an index scan elsewhere. Order
|
|
26
|
+
* here is a hint; the resolver re-applies order+limit PER PARENT after grouping.
|
|
27
|
+
*/
|
|
28
|
+
export interface RelationFetch {
|
|
29
|
+
table: string;
|
|
30
|
+
matchField: string;
|
|
31
|
+
keys: Id[];
|
|
32
|
+
where?: WhereNode[];
|
|
33
|
+
orderBy?: OrderBy;
|
|
34
|
+
select?: string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The read side of an engine, minus relation resolution — the surface a
|
|
39
|
+
* {@link RelationResolver} needs. Kept separate so the resolver can be unit
|
|
40
|
+
* tested against an in-memory fake without a full engine.
|
|
41
|
+
*/
|
|
42
|
+
export interface RowFetcher {
|
|
43
|
+
/** Batched fan-out fetch. See {@link RelationFetch}. */
|
|
44
|
+
fetchRelation(req: RelationFetch): Promise<Row[]>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A transaction handle — the same verbs as the engine, but atomic. */
|
|
48
|
+
export interface EngineTx {
|
|
49
|
+
upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
|
|
50
|
+
patch(table: string, id: Id, patches: unknown[]): Promise<void>;
|
|
51
|
+
delete(table: string, id: Id): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A pluggable local cache backend. SurrealDB (the default) and SQLite both
|
|
56
|
+
* implement this; the rest of the client talks verbs, never SurrealQL.
|
|
57
|
+
*
|
|
58
|
+
* Reactivity is NOT part of this contract: the local cache is passive. The SSP
|
|
59
|
+
* (remote) drives change; `DataModule` writes rows here and re-reads them. The
|
|
60
|
+
* `epoch` field preserves the existing bucket-switch fencing (see
|
|
61
|
+
* `LocalDatabaseService.epoch`): an async chain captures it at start and its
|
|
62
|
+
* write is dropped if the epoch moved (a bucket switch) in between.
|
|
63
|
+
*/
|
|
64
|
+
export interface LocalCacheEngine extends RowFetcher {
|
|
65
|
+
/** Monotonic store generation; bumped on every bucket switch. */
|
|
66
|
+
readonly epoch: number;
|
|
67
|
+
|
|
68
|
+
connect(bucketId: string): Promise<void>;
|
|
69
|
+
switchBucket(bucketId: string): Promise<void>;
|
|
70
|
+
close(): Promise<void>;
|
|
71
|
+
|
|
72
|
+
/** Run `fn` inside a single atomic transaction. */
|
|
73
|
+
transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Materialize a query, including its `.related()` tree (via §3
|
|
77
|
+
* decomposition). Params bind `where` `paramRef`s and any windowing id-set.
|
|
78
|
+
*/
|
|
79
|
+
select(plan: QueryPlan, params?: Record<string, unknown>, opts?: { paintKey?: string }): Promise<Row[]>;
|
|
80
|
+
|
|
81
|
+
/** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
|
|
82
|
+
selectByIds(table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): Promise<Row[]>;
|
|
83
|
+
|
|
84
|
+
/** Single-record read by primary id, or `null`. */
|
|
85
|
+
getById(table: string, id: Id): Promise<Row | null>;
|
|
86
|
+
|
|
87
|
+
upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
|
|
88
|
+
patch(table: string, id: Id, patches: unknown[]): Promise<void>;
|
|
89
|
+
delete(table: string, id: Id): Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The full surface the client's `this.local` field depends on: the
|
|
94
|
+
* engine-neutral {@link LocalCacheEngine} verbs PLUS the legacy
|
|
95
|
+
* SurrealQL/lifecycle methods the not-yet-migrated call sites still use.
|
|
96
|
+
* `SurrealCacheEngine` (subclass of `LocalDatabaseService`) and
|
|
97
|
+
* `SqliteCacheEngine` (via a SurrealQL-vocabulary shim) both satisfy this, so
|
|
98
|
+
* either can back `this.local`.
|
|
99
|
+
*
|
|
100
|
+
* `getClient()` returns the underlying SurrealDB `Surreal` handle where one
|
|
101
|
+
* exists (SurrealDB backend); backends without one (SQLite) throw — it is only
|
|
102
|
+
* used by advanced/DevTools paths, never on the hot path.
|
|
103
|
+
*/
|
|
104
|
+
export interface LocalStore extends LocalCacheEngine {
|
|
105
|
+
/**
|
|
106
|
+
* Whether this engine needs SurrealQL schema provisioning (`DEFINE TABLE`,
|
|
107
|
+
* `DEFINE FIELD`, …) run against it at init / bucket switch. SurrealDB → true;
|
|
108
|
+
* schemaless engines (SQLite creates tables lazily) → false, so the client
|
|
109
|
+
* skips the `LocalMigrator` entirely for them.
|
|
110
|
+
*/
|
|
111
|
+
readonly usesSurqlSchema: boolean;
|
|
112
|
+
query<T extends unknown[]>(
|
|
113
|
+
query: string,
|
|
114
|
+
vars?: Record<string, unknown>,
|
|
115
|
+
opts?: { epoch?: number }
|
|
116
|
+
): Promise<T>;
|
|
117
|
+
execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>, opts?: { epoch?: number }): Promise<T>;
|
|
118
|
+
queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
|
|
119
|
+
switchStore(bucketId: string): Promise<void>;
|
|
120
|
+
beginSwitch(): () => void;
|
|
121
|
+
getEvents(): DatabaseEventSystem;
|
|
122
|
+
getClient(): unknown;
|
|
123
|
+
getConfig(): Sp00kyConfig<any>['database'];
|
|
124
|
+
readonly currentBucketId: string;
|
|
125
|
+
/** Which built-in backend this is. OPTIONAL: absent (custom engines) is
|
|
126
|
+
* reported as `'custom'` by DevTools. More robust than `instanceof` for
|
|
127
|
+
* engines constructed outside this package. */
|
|
128
|
+
readonly engineKind?: 'surrealdb' | 'sqlite' | 'rows';
|
|
129
|
+
/** Engine-specific storage numbers for DevTools (DB file size, per-table
|
|
130
|
+
* row counts). OPTIONAL: only engines with something to report implement it. */
|
|
131
|
+
getStorageDiagnostics?(opts?: { tableCounts?: boolean }): Promise<EngineStorageDiagnostics>;
|
|
132
|
+
/**
|
|
133
|
+
* Durability of this engine's local store. OPTIONAL: engines that don't
|
|
134
|
+
* report it (SurrealDB, custom engines) are treated as `'unknown'` by the
|
|
135
|
+
* client facade, so adding this needs no change on their side.
|
|
136
|
+
*/
|
|
137
|
+
readonly storageHealth?: StorageHealth;
|
|
138
|
+
/**
|
|
139
|
+
* Delete a bucket's persisted store. Never the open one. OPTIONAL and
|
|
140
|
+
* best-effort: used to remove an impersonated user's data from the admin's
|
|
141
|
+
* device once the impersonation ends.
|
|
142
|
+
*/
|
|
143
|
+
dropBucket?(bucketId: string): Promise<void>;
|
|
144
|
+
/** Fires immediately with the current snapshot, then on every change.
|
|
145
|
+
* Returns an unsubscribe function. */
|
|
146
|
+
subscribeToStorageHealth?(cb: (health: StorageHealth) => void): () => void;
|
|
147
|
+
/**
|
|
148
|
+
* Every cached row's `(id, _00_rv)` per table, ids in stable `table:id`
|
|
149
|
+
* form. The in-browser circuit primes and reconciles itself from this on
|
|
150
|
+
* boot instead of re-downloading the working set. OPTIONAL: an engine
|
|
151
|
+
* without it boots the circuit empty, as before.
|
|
152
|
+
*/
|
|
153
|
+
scanVersions?(tables: string[]): Promise<Record<string, [string, number][]>>;
|
|
154
|
+
/**
|
|
155
|
+
* Reset the cached `_00_rv` of every table whose column set (`fingerprints`,
|
|
156
|
+
* see `columnFingerprints`) changed since the store last recorded it, except
|
|
157
|
+
* the rows in `keep`, and record the new sets. Returns the tables reset.
|
|
158
|
+
* For engines that keep bodies across schema changes: a body landed under an
|
|
159
|
+
* older schema lacks the columns it did not know, at the server's version,
|
|
160
|
+
* and would never be fetched again. OPTIONAL: an engine that rebuilds its
|
|
161
|
+
* store on a schema change (SurrealDB) does not need it.
|
|
162
|
+
*/
|
|
163
|
+
resetChangedTables?(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]>;
|
|
164
|
+
/**
|
|
165
|
+
* Circuit snapshot storage, keyed. Lives in the same durable store as the
|
|
166
|
+
* rows (OPFS SQLite), so it is per-bucket by construction, atomic, and
|
|
167
|
+
* readable by follower tabs over the port transport. OPTIONAL: an engine
|
|
168
|
+
* without it primes from `scanVersions` alone.
|
|
169
|
+
*/
|
|
170
|
+
/**
|
|
171
|
+
* What `select(plan, params)` / `selectByIds` answered the last time the app
|
|
172
|
+
* asked at startup, SYNCHRONOUSLY and before the store is open, or `null`.
|
|
173
|
+
* Something to paint from; the read itself stays the answer and must follow.
|
|
174
|
+
* OPTIONAL: only an engine that keeps such a copy (`'rows'`) has them.
|
|
175
|
+
*/
|
|
176
|
+
peekSelect?(plan: QueryPlan, params?: Record<string, unknown>, opts?: { paintKey?: string }): Row[] | null;
|
|
177
|
+
/**
|
|
178
|
+
* The bucket `connect` is about to be called with, told ahead: a store that
|
|
179
|
+
* keeps rows to paint from can then answer {@link peekSelect} before it is
|
|
180
|
+
* open. Ignored by a store that keeps none.
|
|
181
|
+
*/
|
|
182
|
+
expectBucket?(bucketId: string): void;
|
|
183
|
+
peekByIds?(table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): Row[] | null;
|
|
184
|
+
getSnapshot?(key: string): Promise<StoredSnapshot | null>;
|
|
185
|
+
putSnapshot?(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void>;
|
|
186
|
+
deleteSnapshot?(key: string): Promise<void>;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Describes a stored circuit snapshot; what decides whether it is usable. */
|
|
190
|
+
export interface SnapshotMeta {
|
|
191
|
+
/** Bump when the wire shape the circuit reads changes. */
|
|
192
|
+
formatVersion: number;
|
|
193
|
+
/** Hash of the schema the rows were projected under. */
|
|
194
|
+
schemaHash: string;
|
|
195
|
+
savedAt: number;
|
|
196
|
+
/** Highest `_00_rv` per table at save time (diagnostics). */
|
|
197
|
+
maxRv?: Record<string, number>;
|
|
198
|
+
[key: string]: unknown;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export interface StoredSnapshot {
|
|
202
|
+
bytes: Uint8Array;
|
|
203
|
+
meta: SnapshotMeta;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
|
|
207
|
+
export type LocalEngineChoice = 'surrealdb' | 'sqlite' | 'rows' | LocalStore;
|
|
208
|
+
|
|
209
|
+
/** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
|
|
210
|
+
* a guard against a cyclic schema producing unbounded fan-out. */
|
|
211
|
+
export class RelationCycleError extends Error {
|
|
212
|
+
constructor(path: string[]) {
|
|
213
|
+
super(`Relation nesting exceeded safe depth; possible cyclic schema: ${path.join(' -> ')}`);
|
|
214
|
+
this.name = 'RelationCycleError';
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Defensive ceiling on relation nesting depth. A finite plan tree never hits
|
|
219
|
+
* this in practice; it exists so a malformed/cyclic plan fails loudly instead
|
|
220
|
+
* of running away. */
|
|
221
|
+
export const MAX_RELATION_DEPTH = 12;
|
|
222
|
+
|
|
223
|
+
export type { QueryPlan, RelationPlan, WhereNode };
|