@spooky-sync/core 0.0.1-canary.38 → 0.0.1-canary.381
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 +91 -0
- package/README.md +59 -16
- package/dist/index.d.ts +2238 -144
- package/dist/index.js +18149 -2475
- 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 +2082 -39
- 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 +28 -7
- 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/build-globals.d.ts +12 -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/events/index.ts +3 -0
- package/src/index.ts +86 -1
- 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 +538 -14
- 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 +125 -0
- package/src/modules/crdt/crdt.test.ts +546 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +821 -0
- 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 +746 -93
- 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.test.ts +74 -0
- package/src/modules/devtools/versions.ts +110 -0
- package/src/modules/feature-flag/index.test.ts +298 -0
- package/src/modules/feature-flag/index.ts +316 -0
- package/src/modules/ref-tables.test.ts +93 -0
- package/src/modules/ref-tables.ts +91 -0
- 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/query/window-query.test.ts +70 -0
- package/src/query/window-query.ts +208 -0
- 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 +150 -0
- package/src/services/database/local.ts +503 -59
- 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 +224 -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/resilient.ts +8 -1
- package/src/services/persistence/surrealdb.ts +2 -2
- package/src/services/stream-processor/index.ts +801 -63
- package/src/services/stream-processor/permissions.test.ts +47 -0
- package/src/services/stream-processor/permissions.ts +53 -0
- package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
- 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 +57 -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 -394
- 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/sync/policy.test.ts +663 -0
- package/src/sync/policy.ts +515 -0
- 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 +694 -7
- 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 +83 -6
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +63 -2
- 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 +22 -11
- package/src/utils/utils.test.ts +3 -2
- package/tsdown.config.ts +117 -3
- package/vitest.config.ts +48 -0
- package/src/modules/cache/index.ts +0 -241
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -882
- package/src/modules/sync/engine.ts +0 -173
- package/src/modules/sync/events/index.ts +0 -78
- 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 -84
- package/src/modules/sync/sync.ts +0 -422
- package/src/modules/sync/utils.test.ts +0 -311
- package/src/modules/sync/utils.ts +0 -169
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
|
|
5
|
+
import { RecordId, Surreal } from 'surrealdb';
|
|
6
|
+
import { defaultEnv } from '../query/env';
|
|
7
|
+
import { runPure } from '../testing/run-pure';
|
|
8
|
+
import { buildState } from '../testing/build';
|
|
9
|
+
import type { ClientState } from '../state/client-state';
|
|
10
|
+
import type { SealedQuery } from '../utils/surql';
|
|
11
|
+
import type { Vars } from '../kernel/effects';
|
|
12
|
+
import { SqliteCacheEngine } from '../services/database/sqlite-cache-engine';
|
|
13
|
+
import { stubTransport } from '../services/database/sqlite-transport.fixture';
|
|
14
|
+
import { PENDING_WRITE_ORPHAN_MS } from '../kernel/constants';
|
|
15
|
+
import { loadPendingRows, parsePendingRow } from './rows';
|
|
16
|
+
import { mintMutationId } from './mutation-id';
|
|
17
|
+
import { adoptPendingWrites, flushWrite, write } from './write.saga';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Integration: a debounced update must survive the page going away inside its
|
|
21
|
+
* delay. These run the real sagas and execute their transactions on BOTH local
|
|
22
|
+
* engines: a real in-memory SQLite behind the SqliteCacheEngine, and a real
|
|
23
|
+
* SurrealDB-WASM `mem://` store whose `_00_pending_writes` table was never
|
|
24
|
+
* defined (a store provisioned before the table existed).
|
|
25
|
+
*
|
|
26
|
+
* On each: the patch is mirrored to `_00_pending_writes` beside the row; a
|
|
27
|
+
* timely flush moves it into the outbox; and when the page died first, a fresh
|
|
28
|
+
* page (empty memory) adopts the mirror into a replayable outbox row.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const env = defaultEnv({ tables: [{ name: 'doc', columns: { title: { type: 'string', optional: true } } }] } as any);
|
|
32
|
+
const doc = new RecordId('doc', 'd1');
|
|
33
|
+
|
|
34
|
+
interface Engine {
|
|
35
|
+
query(sql: string, vars?: Vars): Promise<unknown>;
|
|
36
|
+
execute(query: SealedQuery<unknown>, vars: Vars): Promise<unknown>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const run = <R>(engine: Engine, saga: Generator<any, R, any>, state: ClientState, now: number) =>
|
|
40
|
+
runPure(saga, {
|
|
41
|
+
state,
|
|
42
|
+
now,
|
|
43
|
+
handlers: {
|
|
44
|
+
'local.query': (e: any) => engine.query(e.sql, e.vars),
|
|
45
|
+
'local.execute': (e: any) => engine.execute(e.query, e.vars),
|
|
46
|
+
'ssp.ingest': () => undefined,
|
|
47
|
+
id: () => mintMutationId(state.tabId),
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
async function scenario(engine: Engine, readRow: () => Promise<Record<string, unknown> | null>): Promise<void> {
|
|
52
|
+
const typed = async (title: string, state: ClientState, now: number) =>
|
|
53
|
+
run(engine, write(env, { kind: 'update', recordId: 'doc:d1', data: { title }, options: { debounced: { delay: 1_000 } } }), state, now);
|
|
54
|
+
const mirrors = async () => ((await engine.query('SELECT * FROM _00_pending_writes')) as unknown[][])[0] ?? [];
|
|
55
|
+
const outbox = async () => (((await engine.query(loadPendingRows())) as unknown[][])[0] ?? []).map(parsePendingRow);
|
|
56
|
+
|
|
57
|
+
// Booting with nothing to adopt is a no-op, even before the table exists.
|
|
58
|
+
const boot = await run(engine, adoptPendingWrites(), buildState(), 0);
|
|
59
|
+
expect(boot.dispatched).toEqual([]);
|
|
60
|
+
|
|
61
|
+
// Typing inside the delay: the row changes at once, the patch is mirrored beside it.
|
|
62
|
+
const a = await typed('He', buildState(), 1_000);
|
|
63
|
+
const b = await typed('Hello', a.state, 1_100);
|
|
64
|
+
expect((await readRow())?.title).toBe('Hello');
|
|
65
|
+
expect(await mirrors()).toHaveLength(1);
|
|
66
|
+
expect(await outbox()).toEqual([]);
|
|
67
|
+
|
|
68
|
+
// The timer fires: the patch moves into the outbox, the mirror is gone.
|
|
69
|
+
const flushed = await run(engine, flushWrite(env, 'doc:d1::title'), b.state, 2_100);
|
|
70
|
+
expect(await mirrors()).toEqual([]);
|
|
71
|
+
expect(await outbox()).toEqual([expect.objectContaining({ mutationType: 'update', recordId: 'doc:d1', data: { title: 'Hello' } })]);
|
|
72
|
+
await engine.query('DELETE _00_pending_mutations');
|
|
73
|
+
|
|
74
|
+
// Typing again, then the page dies before the flush: memory is gone, the mirror is not.
|
|
75
|
+
await typed('Hello world', flushed.state, 3_000);
|
|
76
|
+
const reloaded = { ...buildState(), tabId: 'tab-after-reload' };
|
|
77
|
+
const early = await run(engine, adoptPendingWrites(), reloaded, 3_100);
|
|
78
|
+
expect(early.timers.get('adopt-writes')).toEqual({ ms: 4_000 + PENDING_WRITE_ORPHAN_MS - 3_100, event: { type: 'AdoptPendingWrites' } });
|
|
79
|
+
expect(await outbox()).toEqual([]);
|
|
80
|
+
|
|
81
|
+
const adopted = await run(engine, adoptPendingWrites(), reloaded, 4_000 + PENDING_WRITE_ORPHAN_MS);
|
|
82
|
+
expect(adopted.dispatched).toEqual([{ type: 'Drain' }]);
|
|
83
|
+
expect(await mirrors()).toEqual([]);
|
|
84
|
+
const rows = await outbox();
|
|
85
|
+
expect(rows).toEqual([expect.objectContaining({ mutationType: 'update', recordId: 'doc:d1', data: { title: 'Hello world' } })]);
|
|
86
|
+
expect(adopted.state.outbox.map((i) => i.id)).toEqual([rows[0]!.id]);
|
|
87
|
+
expect((await readRow())?.title).toBe('Hello world');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const noop = () => {};
|
|
91
|
+
|
|
92
|
+
describe('debounced writes survive a dead page: SQLite engine', () => {
|
|
93
|
+
let db: any;
|
|
94
|
+
|
|
95
|
+
beforeAll(async () => {
|
|
96
|
+
const sqlite3: any = await sqlite3InitModule();
|
|
97
|
+
db = new sqlite3.oo1.DB(':memory:', 'c');
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
afterAll(() => db?.close());
|
|
101
|
+
|
|
102
|
+
it('mirrors, flushes, and adopts', async () => {
|
|
103
|
+
const logger: any = { debug: noop, info: noop, warn: noop, error: noop, trace: noop };
|
|
104
|
+
logger.child = () => logger;
|
|
105
|
+
const engine = new SqliteCacheEngine({ namespace: 'n', database: 'd' } as any, logger);
|
|
106
|
+
stubTransport(engine, (type, payload: any) => {
|
|
107
|
+
switch (type) {
|
|
108
|
+
case 'open':
|
|
109
|
+
// As the worker does: system tables exist from the open on.
|
|
110
|
+
for (const t of payload.systemTables as string[]) db.exec({ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
|
|
111
|
+
return { persisted: true };
|
|
112
|
+
case 'exec':
|
|
113
|
+
return { rows: db.exec({ sql: payload.sql, bind: payload.bind, rowMode: 'object', returnValue: 'resultRows' }) };
|
|
114
|
+
case 'run':
|
|
115
|
+
db.exec({ sql: payload.sql, bind: payload.bind });
|
|
116
|
+
return {};
|
|
117
|
+
case 'batch':
|
|
118
|
+
for (const stmt of payload as { sql: string; bind?: unknown[] }[]) db.exec({ sql: stmt.sql, bind: stmt.bind });
|
|
119
|
+
return {};
|
|
120
|
+
default:
|
|
121
|
+
return {};
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
await engine.connect('anon');
|
|
125
|
+
await engine.upsert('doc', doc, { title: '' }, 'replace');
|
|
126
|
+
await scenario(
|
|
127
|
+
{ query: (sql, vars) => engine.query(sql, vars), execute: (q, v) => engine.execute(q, v) },
|
|
128
|
+
async () => ((await engine.getById('doc', doc)) as Record<string, unknown>) ?? null
|
|
129
|
+
);
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
describe('debounced writes survive a dead page: SurrealDB-WASM engine', () => {
|
|
134
|
+
let db: Surreal;
|
|
135
|
+
|
|
136
|
+
beforeAll(async () => {
|
|
137
|
+
// The wasm engine loads its binary with `fetch(new URL(..., import.meta.url))`,
|
|
138
|
+
// and Node's fetch has no `file:` scheme: serve that one read from disk.
|
|
139
|
+
const realFetch = globalThis.fetch;
|
|
140
|
+
vi.stubGlobal('fetch', async (input: unknown, init?: RequestInit) => {
|
|
141
|
+
const url = input instanceof URL ? input : new URL(String(input));
|
|
142
|
+
if (url.protocol === 'file:') return new Response(await readFile(fileURLToPath(url)));
|
|
143
|
+
return realFetch(input as RequestInfo, init);
|
|
144
|
+
});
|
|
145
|
+
const { createWasmEngines } = await import('@surrealdb/wasm');
|
|
146
|
+
db = new Surreal({ engines: createWasmEngines() });
|
|
147
|
+
await db.connect('mem://');
|
|
148
|
+
await db.use({ namespace: 'n', database: 'd' });
|
|
149
|
+
await db.query(`
|
|
150
|
+
DEFINE TABLE doc SCHEMAFULL;
|
|
151
|
+
DEFINE FIELD title ON doc TYPE option<string>;
|
|
152
|
+
DEFINE FIELD _00_rv ON doc TYPE option<int>;
|
|
153
|
+
DEFINE TABLE _00_pending_mutations SCHEMALESS;
|
|
154
|
+
CREATE doc:d1 SET title = '';
|
|
155
|
+
`);
|
|
156
|
+
}, 60_000);
|
|
157
|
+
|
|
158
|
+
afterAll(async () => {
|
|
159
|
+
await db?.close();
|
|
160
|
+
vi.unstubAllGlobals();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('mirrors, flushes, and adopts', async () => {
|
|
164
|
+
await scenario(
|
|
165
|
+
{
|
|
166
|
+
query: (sql, vars) => db.query(sql, vars) as unknown as Promise<unknown>,
|
|
167
|
+
execute: async (q, v) => q.extract((await db.query(q.sql, v)) as unknown[]),
|
|
168
|
+
},
|
|
169
|
+
async () => {
|
|
170
|
+
const [row] = (await db.query('SELECT * FROM ONLY $id', { id: doc })) as [Record<string, unknown>];
|
|
171
|
+
return row ?? null;
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { RecordId } from 'surrealdb';
|
|
3
|
+
import { runPure } from '../testing/run-pure';
|
|
4
|
+
import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
|
|
5
|
+
import * as R from '../state/reducers';
|
|
6
|
+
import { defaultEnv } from '../query/env';
|
|
7
|
+
import { drain, loadOutbox, refreshFailedCount, rollback } from './push.saga';
|
|
8
|
+
import type { StatementResult } from '../kernel/effects';
|
|
9
|
+
import { BATCH_SKIPPED, type PendingMutationRow } from './rows';
|
|
10
|
+
|
|
11
|
+
const env = defaultEnv({ tables: [{ name: 'thing', columns: {} }] } as any, { outboxBatchSize: 2 });
|
|
12
|
+
const ok = (result: unknown = null): StatementResult => ({ status: 'OK', result });
|
|
13
|
+
const err = (error: string): StatementResult => ({ status: 'ERR', error });
|
|
14
|
+
/** What SurrealDB answers for a chained statement whose predecessor failed. */
|
|
15
|
+
const skipped = (): StatementResult => err(`An error occurred: ${BATCH_SKIPPED}`);
|
|
16
|
+
/** The row numbers a pushed batch carries, from its `$id<i>` vars. */
|
|
17
|
+
const pushedRows = (vars: Record<string, unknown>) =>
|
|
18
|
+
Object.keys(vars)
|
|
19
|
+
.filter((k) => /^id\d+$/.test(k))
|
|
20
|
+
.map((k) => String((vars[k] as RecordId).id));
|
|
21
|
+
const pendingRow = (n: number, type: PendingMutationRow['mutationType'] = 'create', extra: Partial<PendingMutationRow> = {}) => ({
|
|
22
|
+
id: `_00_pending_mutations:m${n}`,
|
|
23
|
+
mutationType: type,
|
|
24
|
+
recordId: `thing:${n}`,
|
|
25
|
+
tableName: 'thing',
|
|
26
|
+
data: type === 'delete' ? undefined : { a: n },
|
|
27
|
+
beforeRecord: type === 'create' ? undefined : { id: `thing:${n}`, a: 0, _00_rv: 7 },
|
|
28
|
+
createdAt: 1,
|
|
29
|
+
v: 2,
|
|
30
|
+
...extra,
|
|
31
|
+
});
|
|
32
|
+
const items = (...ns: number[]) => ns.map((n) => buildOutboxItem({ id: `_00_pending_mutations:m${n}`, recordId: `thing:${n}`, type: 'create' }));
|
|
33
|
+
const stateWith = (rows: number[], ...extra: Parameters<typeof buildState>[1][]) =>
|
|
34
|
+
buildState([buildEntry({ def: { hash: 'q', tableName: 'thing' } })], R.outboxReplace(items(...rows)), ...extra);
|
|
35
|
+
|
|
36
|
+
describe('drain', () => {
|
|
37
|
+
it('re-types stored payloads from the schema before pushing (a stored record field is a string)', async () => {
|
|
38
|
+
const typedEnv = defaultEnv({ tables: [{ name: 'thing', columns: { owner: { recordId: true } } }] } as any, { outboxBatchSize: 2 });
|
|
39
|
+
let vars: any = null;
|
|
40
|
+
await runPure(drain(typedEnv), {
|
|
41
|
+
state: stateWith([1]),
|
|
42
|
+
handlers: {
|
|
43
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [[pendingRow(1, 'create', { data: { owner: 'user:u1' } })]] : []),
|
|
44
|
+
'remote.query': (e: any) => ((vars = e.vars), [ok()]),
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
expect(vars.d0_owner).toEqual(new RecordId('user', 'u1'));
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('pushes batches in FIFO order, acks each accepted row, deletes its pending row, then loops', async () => {
|
|
51
|
+
const pushed: string[] = [];
|
|
52
|
+
const out = await runPure(drain(env), {
|
|
53
|
+
state: stateWith([1, 2, 3]),
|
|
54
|
+
now: 500,
|
|
55
|
+
handlers: {
|
|
56
|
+
'local.query': (e: any) => {
|
|
57
|
+
if (e.sql === 'SELECT * FROM $ids') return [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))];
|
|
58
|
+
return [];
|
|
59
|
+
},
|
|
60
|
+
'remote.query': (e: any) => {
|
|
61
|
+
pushed.push(e.sql);
|
|
62
|
+
return e.sql.split(';\n').map(() => ok());
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
expect(pushed).toEqual([
|
|
67
|
+
`LET $ok0 = { CREATE ONLY $id0 SET a = $d0_a; true };\nLET $ok1 = { IF !$ok0 { THROW "${BATCH_SKIPPED}" }; CREATE ONLY $id1 SET a = $d1_a; true }`,
|
|
68
|
+
'LET $ok0 = { CREATE ONLY $id0 SET a = $d0_a; true }',
|
|
69
|
+
]);
|
|
70
|
+
expect(out.state.outbox.every((i) => i.status === 'acked' && i.ackedAt === 500)).toBe(true);
|
|
71
|
+
expect(out.log.filter((e) => e.kind === 'local.query' && (e as any).sql === 'DELETE $mid')).toHaveLength(3);
|
|
72
|
+
expect(out.emitted.filter((e) => e.type === 'mutation:settled')).toHaveLength(3);
|
|
73
|
+
expect(out.timers.get('ack-prune')).toEqual({ ms: 30_000, event: { type: 'AckPrune' } });
|
|
74
|
+
expect(out.dispatched.filter((d) => d.type === 'SyncOutcome')).toEqual([{ type: 'SyncOutcome', ok: true, error: undefined }, { type: 'SyncOutcome', ok: true, error: undefined }]);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('a rejected statement rolls back only that row; the rows the server skipped after it go out again at once', async () => {
|
|
78
|
+
const pushed: string[][] = [];
|
|
79
|
+
const out = await runPure(drain(env), {
|
|
80
|
+
state: stateWith([1, 2, 3]),
|
|
81
|
+
handlers: {
|
|
82
|
+
'local.query': (e: any) =>
|
|
83
|
+
e.sql === 'SELECT * FROM $ids' ? [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))] : [],
|
|
84
|
+
'remote.query': (e: any) => {
|
|
85
|
+
pushed.push(pushedRows(e.vars));
|
|
86
|
+
return pushed.length === 1 ? [err('permission denied'), skipped()] : e.sql.split(';\n').map(() => ok());
|
|
87
|
+
},
|
|
88
|
+
'local.execute': () => undefined,
|
|
89
|
+
'ssp.ingest': () => undefined,
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
expect(pushed).toEqual([['1', '2'], ['2', '3']]);
|
|
93
|
+
expect(out.state.outbox.map((i) => [i.id, i.status, i.attempts])).toEqual([
|
|
94
|
+
['_00_pending_mutations:m2', 'acked', 0],
|
|
95
|
+
['_00_pending_mutations:m3', 'acked', 0],
|
|
96
|
+
]);
|
|
97
|
+
expect(out.state.failedCount).toBe(1);
|
|
98
|
+
expect(out.emitted.filter((e) => e.type === 'mutation:rolled-back')).toEqual([
|
|
99
|
+
expect.objectContaining({ mutationId: '_00_pending_mutations:m1', error: 'permission denied' }),
|
|
100
|
+
]);
|
|
101
|
+
expect(out.timers.has('outbox')).toBe(false);
|
|
102
|
+
expect(out.dispatched.filter((d) => d.type === 'SyncOutcome').every((d: any) => d.ok)).toBe(true);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('a CRDT edit-log CREATE that finds its row already there is acked, any other duplicate rolls back', async () => {
|
|
106
|
+
const logEnv = defaultEnv({ tables: [{ name: 'thing', columns: {} }, { name: 'doc__crdt_log', columns: {} }] } as any, { outboxBatchSize: 2 });
|
|
107
|
+
const logRow = pendingRow(1, 'create', { tableName: 'doc__crdt_log', recordId: 'doc__crdt_log:1' });
|
|
108
|
+
let calls = 0;
|
|
109
|
+
const out = await runPure(drain(logEnv), {
|
|
110
|
+
state: stateWith([1, 2]),
|
|
111
|
+
handlers: {
|
|
112
|
+
'local.query': (e: any) =>
|
|
113
|
+
e.sql === 'SELECT * FROM $ids' ? [[logRow, pendingRow(2)].filter((r) => e.vars.ids.some((id: RecordId) => r.id.endsWith(String(id.id))))] : [],
|
|
114
|
+
// The duplicate log row still stops the chain on the server: row 2 goes again on its own.
|
|
115
|
+
'remote.query': () =>
|
|
116
|
+
++calls === 1 ? [err('Database record `doc__crdt_log:1` already exists'), skipped()] : [err('Database record `thing:2` already exists')],
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
expect(calls).toBe(2);
|
|
120
|
+
expect(out.state.outbox.find((i) => i.id === '_00_pending_mutations:m1')?.status).toBe('acked');
|
|
121
|
+
expect(out.state.outbox.some((i) => i.id === '_00_pending_mutations:m2')).toBe(false);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('transport failures keep the tail queued behind a backoff timer (thrown, or a network ERR mid-batch, or a short result list)', async () => {
|
|
125
|
+
const thrown = await runPure(drain(env), {
|
|
126
|
+
state: stateWith([1, 2]),
|
|
127
|
+
handlers: {
|
|
128
|
+
'local.query': () => [[pendingRow(1), pendingRow(2)]],
|
|
129
|
+
'remote.query': () => {
|
|
130
|
+
throw new Error('socket closed');
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
expect(thrown.state.outbox.map((i) => i.status)).toEqual(['pending', 'pending']);
|
|
135
|
+
expect(thrown.state.outbox[0].attempts).toBe(1);
|
|
136
|
+
// No answer: the server may have committed any of them.
|
|
137
|
+
expect(thrown.state.outbox.map((i) => i.inDoubt)).toEqual([true, true]);
|
|
138
|
+
expect(thrown.timers.get('outbox')).toEqual({ ms: 500, event: { type: 'Drain' } });
|
|
139
|
+
expect(thrown.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('socket closed') }]);
|
|
140
|
+
const mid = await runPure(drain(env), {
|
|
141
|
+
state: stateWith([1, 2]),
|
|
142
|
+
handlers: { 'local.query': () => [[pendingRow(1), pendingRow(2)]], 'remote.query': () => [ok(), err('connection reset')] },
|
|
143
|
+
});
|
|
144
|
+
expect(mid.state.outbox.map((i) => [i.status, i.attempts])).toEqual([['acked', 0], ['pending', 1]]);
|
|
145
|
+
// A failed statement did not commit, so its row is not in doubt.
|
|
146
|
+
expect(mid.state.outbox[1].inDoubt).toBeUndefined();
|
|
147
|
+
expect(mid.timers.get('outbox')!.ms).toBe(500);
|
|
148
|
+
const short = await runPure(drain(env), {
|
|
149
|
+
state: stateWith([1, 2]),
|
|
150
|
+
handlers: { 'local.query': () => [[pendingRow(1), pendingRow(2)]], 'remote.query': () => [ok()] },
|
|
151
|
+
});
|
|
152
|
+
expect(short.state.outbox.map((i) => [i.status, i.inDoubt])).toEqual([['acked', undefined], ['pending', true]]);
|
|
153
|
+
const undefinedRows = await runPure(drain(env), { state: stateWith([1]), handlers: { 'local.query': () => undefined } });
|
|
154
|
+
expect(undefinedRows.state.outbox).toEqual([]);
|
|
155
|
+
const notArray = await runPure(drain(env), {
|
|
156
|
+
state: stateWith([1]),
|
|
157
|
+
handlers: { 'local.query': () => [[pendingRow(1)]], 'remote.query': () => 'nope' },
|
|
158
|
+
});
|
|
159
|
+
expect(notArray.timers.has('outbox')).toBe(true);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('a push whose answer was lost goes out again with CREATEs that accept their own earlier commit', async () => {
|
|
163
|
+
const pushed: string[] = [];
|
|
164
|
+
const rowsOf = (e: any) => [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))];
|
|
165
|
+
const out = await runPure(drain(env), {
|
|
166
|
+
state: stateWith([1, 2]),
|
|
167
|
+
handlers: {
|
|
168
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? rowsOf(e) : []),
|
|
169
|
+
'remote.query': (e: any) => {
|
|
170
|
+
pushed.push(e.sql);
|
|
171
|
+
// The server ran the batch; the answer never came back.
|
|
172
|
+
if (pushed.length === 1) throw new Error('Remote request timed out after 15000ms');
|
|
173
|
+
return [ok(), ok()];
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
expect(out.timers.get('outbox')).toEqual({ ms: 500, event: { type: 'Drain' } });
|
|
178
|
+
const again = await runPure(drain(env), {
|
|
179
|
+
state: out.state,
|
|
180
|
+
handlers: {
|
|
181
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? rowsOf(e) : []),
|
|
182
|
+
'remote.query': (e: any) => (pushed.push(e.sql), [ok(), ok()]),
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
const tolerant = (i: number) =>
|
|
186
|
+
`LET $was${i} = (SELECT * FROM ONLY $id${i}); IF ($was${i} = NONE) OR ($was${i}.a != $d${i}_a) { CREATE ONLY $id${i} SET a = $d${i}_a }`;
|
|
187
|
+
expect(pushed[0]).not.toContain('$was');
|
|
188
|
+
expect(pushed[1]).toBe(`LET $ok0 = { ${tolerant(0)}; true };\nLET $ok1 = { IF !$ok0 { THROW "${BATCH_SKIPPED}" }; ${tolerant(1)}; true }`);
|
|
189
|
+
expect(again.emitted.filter((e) => e.type === 'mutation:rolled-back')).toEqual([]);
|
|
190
|
+
expect(again.state.outbox.map((i) => i.status)).toEqual(['acked', 'acked']);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it('a request rejected as a whole with an application error rolls back the head and continues', async () => {
|
|
194
|
+
let calls = 0;
|
|
195
|
+
const out = await runPure(drain(env), {
|
|
196
|
+
state: stateWith([1, 2]),
|
|
197
|
+
handlers: {
|
|
198
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))] : []),
|
|
199
|
+
'remote.query': () => {
|
|
200
|
+
calls++;
|
|
201
|
+
if (calls === 1) throw 'Parse error at line 1';
|
|
202
|
+
return [ok()];
|
|
203
|
+
},
|
|
204
|
+
'local.execute': () => undefined,
|
|
205
|
+
'ssp.ingest': () => undefined,
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
expect(calls).toBe(2);
|
|
209
|
+
expect(out.state.failedCount).toBe(1);
|
|
210
|
+
expect(out.state.outbox.map((i) => [i.id, i.status])).toEqual([['_00_pending_mutations:m2', 'acked']]);
|
|
211
|
+
const asError = await runPure(drain(env), {
|
|
212
|
+
state: stateWith([1]),
|
|
213
|
+
handlers: {
|
|
214
|
+
'local.query': () => [[pendingRow(1)]],
|
|
215
|
+
'remote.query': () => {
|
|
216
|
+
throw new Error('Parse error at line 1');
|
|
217
|
+
},
|
|
218
|
+
'local.execute': (e: any) => {
|
|
219
|
+
if (e.vars.failed) expect(e.vars.failed.error.message).toBe('Parse error at line 1');
|
|
220
|
+
},
|
|
221
|
+
'ssp.ingest': () => undefined,
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
expect(asError.state.failedCount).toBe(1);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it('skips pending rows the store no longer has, does nothing as a follower or when empty, tolerates a failed row delete', async () => {
|
|
228
|
+
const gone = await runPure(drain(env), { state: stateWith([1]), handlers: { 'local.query': () => [[]] } });
|
|
229
|
+
expect(gone.state.outbox).toEqual([]);
|
|
230
|
+
expect(gone.log.filter((e) => e.kind === 'remote.query')).toHaveLength(0);
|
|
231
|
+
const follower = await runPure(drain(env), { state: { ...stateWith([1]), tabRole: 'follower' } });
|
|
232
|
+
expect(follower.log.filter((e) => e.kind === 'local.query')).toHaveLength(0);
|
|
233
|
+
const empty = await runPure(drain(env), { state: buildState() });
|
|
234
|
+
expect(empty.log.filter((e) => e.kind === 'local.query')).toHaveLength(0);
|
|
235
|
+
const delFail = await runPure(drain(env), {
|
|
236
|
+
state: stateWith([1]),
|
|
237
|
+
handlers: {
|
|
238
|
+
'local.query': (e: any) => {
|
|
239
|
+
if (e.sql === 'DELETE $mid') throw new Error('locked');
|
|
240
|
+
return [[pendingRow(1)]];
|
|
241
|
+
},
|
|
242
|
+
'remote.query': () => [ok()],
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
expect(delFail.state.outbox[0].status).toBe('acked');
|
|
246
|
+
expect(delFail.emitted).toContainEqual(expect.objectContaining({ level: 'error' }));
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
describe('rollback', () => {
|
|
251
|
+
it('create: tray move first, local delete, circuit DELETE, version dropped, owner relay when leading', async () => {
|
|
252
|
+
const order: string[] = [];
|
|
253
|
+
const state = { ...stateWith([1]), tabRole: 'leader' as const, tabId: 'tab-a' };
|
|
254
|
+
const row = pendingRow(1, 'create', { id: '_00_pending_mutations:1700000000000_0001_tabz' });
|
|
255
|
+
const out = await runPure(rollback(env, row, { message: 'denied', kind: 'application' }), {
|
|
256
|
+
state: R.setVersions([['thing:1', 1]])(state),
|
|
257
|
+
handlers: {
|
|
258
|
+
'local.execute': (e: any) => void order.push(e.query.sql.includes('_00_failed') || e.query.sql.includes('CREATE ONLY $fid') ? 'tray' : 'revert'),
|
|
259
|
+
'ssp.ingest': (e: any) => void order.push(`circuit:${e.records[0].op}`),
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
expect(order).toEqual(['tray', 'revert', 'circuit:DELETE']);
|
|
263
|
+
expect(out.state.versions.has('thing:1')).toBe(false);
|
|
264
|
+
expect(out.state.failedCount).toBe(1);
|
|
265
|
+
expect(out.state.dirty.has('q')).toBe(true);
|
|
266
|
+
expect(out.emitted).toContainEqual({ type: 'tabs:sendTo', tabId: 'tabz', message: expect.objectContaining({ type: 'mutation-rolled-back' }) });
|
|
267
|
+
expect(out.emitted).toContainEqual({ type: 'tabs:broadcast', message: { type: 'ingest', records: [expect.objectContaining({ op: 'DELETE' })] } });
|
|
268
|
+
expect(out.emitted).toContainEqual({ type: 'tray:changed', count: 1 });
|
|
269
|
+
expect(out.emitted).toContainEqual({ type: 'tabs:broadcast', message: { type: 'failed-mutations-changed', count: 1 } });
|
|
270
|
+
});
|
|
271
|
+
it('update / delete restore beforeRecord and its version; legacy rows read the server row (or end partial)', async () => {
|
|
272
|
+
const upd = await runPure(rollback(env, pendingRow(1, 'update'), { message: 'x', kind: 'application' }), {
|
|
273
|
+
state: stateWith([1]),
|
|
274
|
+
handlers: { 'local.execute': () => undefined, 'ssp.ingest': (e: any) => expect(e.records[0].op).toBe('UPDATE') },
|
|
275
|
+
});
|
|
276
|
+
expect(upd.state.versions.get('thing:1')).toBe(7);
|
|
277
|
+
const del = await runPure(rollback(env, pendingRow(1, 'delete'), { message: 'x', kind: 'application' }), {
|
|
278
|
+
state: stateWith([1]),
|
|
279
|
+
handlers: { 'local.execute': () => undefined, 'ssp.ingest': (e: any) => expect(e.records[0].op).toBe('CREATE') },
|
|
280
|
+
});
|
|
281
|
+
expect(del.state.versions.get('thing:1')).toBe(7);
|
|
282
|
+
const legacy = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
|
|
283
|
+
state: stateWith([1]),
|
|
284
|
+
handlers: {
|
|
285
|
+
'remote.query': () => [ok({ id: new RecordId('thing', '1'), a: 9, _00_rv: 2 })],
|
|
286
|
+
'local.execute': (e: any) => {
|
|
287
|
+
if (e.query.sql.includes('CREATE ONLY $fid')) expect(e.vars.failed.revert).toBe('full');
|
|
288
|
+
},
|
|
289
|
+
'ssp.ingest': () => undefined,
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
expect(legacy.state.versions.get('thing:1')).toBe(2);
|
|
293
|
+
const partial = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
|
|
294
|
+
state: stateWith([1]),
|
|
295
|
+
handlers: {
|
|
296
|
+
'remote.query': () => {
|
|
297
|
+
throw new Error('offline');
|
|
298
|
+
},
|
|
299
|
+
'local.execute': (e: any) => expect(e.vars.failed.revert).toBe('partial'),
|
|
300
|
+
'ssp.ingest': () => undefined,
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
expect(partial.log.filter((e) => e.kind === 'local.execute')).toHaveLength(1);
|
|
304
|
+
const errRow = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
|
|
305
|
+
state: stateWith([1]),
|
|
306
|
+
handlers: { 'remote.query': () => [err('nope')], 'local.execute': () => undefined, 'ssp.ingest': () => undefined },
|
|
307
|
+
});
|
|
308
|
+
expect(errRow.state.failedCount).toBe(1);
|
|
309
|
+
});
|
|
310
|
+
it('every local step is best-effort: tray move, revert and circuit failures are logged', async () => {
|
|
311
|
+
const out = await runPure(rollback(env, pendingRow(1, 'update'), { message: 'x', kind: 'unreplayable' }), {
|
|
312
|
+
state: stateWith([1]),
|
|
313
|
+
handlers: {
|
|
314
|
+
'local.execute': () => {
|
|
315
|
+
throw new Error('disk');
|
|
316
|
+
},
|
|
317
|
+
'ssp.ingest': () => {
|
|
318
|
+
throw new Error('wasm');
|
|
319
|
+
},
|
|
320
|
+
},
|
|
321
|
+
});
|
|
322
|
+
expect(out.emitted.filter((e) => e.type === 'log')).toHaveLength(3);
|
|
323
|
+
expect(out.state.outbox).toEqual([]);
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
describe('loadOutbox / refreshFailedCount', () => {
|
|
328
|
+
it('mirrors pending rows, sends unreplayable ones to the tray, refreshes the count, starts a drain', async () => {
|
|
329
|
+
const out = await runPure(loadOutbox(env), {
|
|
330
|
+
state: buildState(),
|
|
331
|
+
handlers: {
|
|
332
|
+
'local.query': (e: any) => {
|
|
333
|
+
if (e.sql.startsWith('SELECT * FROM _00_pending_mutations'))
|
|
334
|
+
return [[pendingRow(1), { id: '_00_pending_mutations:bad', mutationType: 'create', recordId: 'thing:9' }, { tableName: 'thing' }, { mutationType: 'delete' }, 'junk']];
|
|
335
|
+
if (e.sql.startsWith('SELECT count()')) return [[{ count: 4 }]];
|
|
336
|
+
return [];
|
|
337
|
+
},
|
|
338
|
+
'local.execute': () => undefined,
|
|
339
|
+
'ssp.ingest': () => undefined,
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
expect(out.state.outbox.map((i) => i.id)).toEqual(['_00_pending_mutations:m1']);
|
|
343
|
+
expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '_00_pending_mutations:bad' }));
|
|
344
|
+
expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '' }));
|
|
345
|
+
expect(out.state.failedCount).toBe(4);
|
|
346
|
+
expect(out.dispatched).toEqual([{ type: 'Drain' }, { type: 'AdoptPendingWrites' }]);
|
|
347
|
+
const empty = await runPure(loadOutbox(env), { state: buildState(), handlers: { 'local.query': () => [] } });
|
|
348
|
+
expect(empty.dispatched).toEqual([{ type: 'AdoptPendingWrites' }]);
|
|
349
|
+
const missingTable = await runPure(refreshFailedCount(), {
|
|
350
|
+
state: R.setFailedCount(2)(buildState()),
|
|
351
|
+
handlers: {
|
|
352
|
+
'local.query': () => {
|
|
353
|
+
throw new Error('no table');
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
});
|
|
357
|
+
expect(missingTable.state.failedCount).toBe(2);
|
|
358
|
+
const noRows = await runPure(refreshFailedCount(), { state: R.setFailedCount(2)(buildState()), handlers: { 'local.query': () => [[]] } });
|
|
359
|
+
expect(noRows.state.failedCount).toBe(0);
|
|
360
|
+
});
|
|
361
|
+
});
|