@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,245 @@
|
|
|
1
|
+
import type { Saga } from '../kernel/saga';
|
|
2
|
+
import type { StatementResult } from '../kernel/effects';
|
|
3
|
+
import { fx } from '../kernel/effects';
|
|
4
|
+
import { ACK_GRACE_MS, backoffMs } from '../kernel/constants';
|
|
5
|
+
import type { ClientState, OutboxItem } from '../state/client-state';
|
|
6
|
+
import * as R from '../state/reducers';
|
|
7
|
+
import { classifySyncError } from '../utils/error-classification';
|
|
8
|
+
import type { SagaEnv } from '../query/env';
|
|
9
|
+
import { columnsFor } from '../query/env';
|
|
10
|
+
import { mutationOwnerTabId } from './mutation-id';
|
|
11
|
+
import {
|
|
12
|
+
buildFailedRow,
|
|
13
|
+
deletePendingRow,
|
|
14
|
+
hydrateRowData,
|
|
15
|
+
loadPendingRows,
|
|
16
|
+
moveToFailedTx,
|
|
17
|
+
parsePendingRow,
|
|
18
|
+
parseStoredRecordId,
|
|
19
|
+
planRevert,
|
|
20
|
+
remoteBatch,
|
|
21
|
+
toOutboxItem,
|
|
22
|
+
BATCH_SKIPPED,
|
|
23
|
+
FAILED_TABLE,
|
|
24
|
+
type PendingMutationRow,
|
|
25
|
+
} from './rows';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Boot / bucket switch: mirror the outbox table into state. Rows that can
|
|
29
|
+
* never be replayed (a create without its payload) go straight to the tray.
|
|
30
|
+
* Debounced patches a dead page left in `_00_pending_writes` are adopted next.
|
|
31
|
+
*/
|
|
32
|
+
export function* loadOutbox(env: SagaEnv): Saga<void> {
|
|
33
|
+
const res = (yield fx.local.query(loadPendingRows())) as unknown[];
|
|
34
|
+
const raw = Array.isArray(res?.[0]) ? (res[0] as unknown[]) : [];
|
|
35
|
+
const items: OutboxItem[] = [];
|
|
36
|
+
const unreplayable: Array<Record<string, unknown>> = [];
|
|
37
|
+
for (const row of raw) {
|
|
38
|
+
const parsed = parsePendingRow(row);
|
|
39
|
+
if (parsed) items.push(toOutboxItem(parsed));
|
|
40
|
+
else if (row && typeof row === 'object') unreplayable.push(row as Record<string, unknown>);
|
|
41
|
+
}
|
|
42
|
+
yield fx.state.update(R.outboxReplace(items));
|
|
43
|
+
for (const row of unreplayable) {
|
|
44
|
+
const stub: PendingMutationRow = {
|
|
45
|
+
id: String(row.id ?? ''),
|
|
46
|
+
mutationType: (row.mutationType as PendingMutationRow['mutationType']) ?? 'create',
|
|
47
|
+
recordId: String(row.recordId ?? ''),
|
|
48
|
+
tableName: String(row.tableName ?? String(row.recordId ?? '').split(':')[0]),
|
|
49
|
+
createdAt: 0,
|
|
50
|
+
v: 1,
|
|
51
|
+
};
|
|
52
|
+
yield* rollback(env, stub, { message: 'pending mutation is not replayable', kind: 'unreplayable' });
|
|
53
|
+
}
|
|
54
|
+
yield* refreshFailedCount();
|
|
55
|
+
if (items.length > 0) yield fx.dispatch({ type: 'Drain' });
|
|
56
|
+
yield fx.dispatch({ type: 'AdoptPendingWrites' });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function* refreshFailedCount(): Saga<void> {
|
|
60
|
+
try {
|
|
61
|
+
const res = (yield fx.local.query(`SELECT count() FROM ${FAILED_TABLE} GROUP ALL`)) as unknown[];
|
|
62
|
+
const row = Array.isArray(res?.[0]) ? (res[0] as Array<{ count?: number }>)[0] : undefined;
|
|
63
|
+
yield fx.state.update(R.setFailedCount(typeof row?.count === 'number' ? row.count : 0));
|
|
64
|
+
} catch {
|
|
65
|
+
// The tray table may not exist yet on a fresh store; the count stays as is.
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const ERR = (r: StatementResult | undefined): string | null => (r && r.status === 'ERR' ? r.error : null);
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A CRDT edit-log row (`<table>__crdt_log`) is written once and never changes,
|
|
73
|
+
* so a CREATE retried after its first attempt committed (and only the answer
|
|
74
|
+
* was lost) finds it already there: that is a success, not a rejection.
|
|
75
|
+
* `remoteBatch` already makes such a CREATE a no-op on the server; this covers
|
|
76
|
+
* a row the user may create but not read back, where that check cannot see it.
|
|
77
|
+
*/
|
|
78
|
+
const isRepeatedLogCreate = (row: { mutationType: string; tableName: string }, err: string): boolean =>
|
|
79
|
+
row.mutationType === 'create' && row.tableName.endsWith('__crdt_log') && /already exists/i.test(err);
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Drain the outbox: one serial lane, FIFO, up to `outboxBatchSize` statements
|
|
83
|
+
* per request, per-statement outcome. Accepted rows are acked (they stay in
|
|
84
|
+
* the overlay until membership names them), rejected rows are rolled back,
|
|
85
|
+
* a transport failure leaves the unsent tail queued behind a backoff timer.
|
|
86
|
+
* The server stops a batch at its first failed statement (`remoteBatch`), so
|
|
87
|
+
* the rows after a rejection are sent again at once, and a re-sent row behind
|
|
88
|
+
* a retryable failure never ran before, so it cannot read "already exists".
|
|
89
|
+
*
|
|
90
|
+
* A request that throws a transport error (the push timeout, a dropped
|
|
91
|
+
* socket) may still have committed on the server, and so may one sent by a
|
|
92
|
+
* session that died before its answer. Those rows are marked in doubt
|
|
93
|
+
* (`OutboxItem.inDoubt`, every row loaded from the store is), and their
|
|
94
|
+
* re-sent CREATE accepts the row already on the server when it holds what the
|
|
95
|
+
* CREATE would write, instead of failing "already exists" and rolling back a
|
|
96
|
+
* write the server kept.
|
|
97
|
+
*/
|
|
98
|
+
export function* drain(env: SagaEnv): Saga<void> {
|
|
99
|
+
for (;;) {
|
|
100
|
+
const state = (yield fx.state.read((s) => s)) as ClientState;
|
|
101
|
+
if (state.tabRole === 'follower') return;
|
|
102
|
+
const batch = state.outbox.filter((i) => i.status === 'pending').slice(0, env.outboxBatchSize);
|
|
103
|
+
if (batch.length === 0) return;
|
|
104
|
+
const rowsRes = (yield fx.local.query('SELECT * FROM $ids', { ids: batch.map((i) => parseStoredRecordId(i.id)) })) as unknown[];
|
|
105
|
+
const rawRows = Array.isArray(rowsRes?.[0]) ? (rowsRes[0] as unknown[]) : [];
|
|
106
|
+
const byId = new Map<string, PendingMutationRow>();
|
|
107
|
+
for (const raw of rawRows) {
|
|
108
|
+
const parsed = parsePendingRow(raw);
|
|
109
|
+
if (parsed) byId.set(parsed.id, parsed);
|
|
110
|
+
}
|
|
111
|
+
const rows: PendingMutationRow[] = [];
|
|
112
|
+
for (const item of batch) {
|
|
113
|
+
const row = byId.get(item.id);
|
|
114
|
+
if (row) rows.push(hydrateRowData(row, columnsFor(env, row.tableName)));
|
|
115
|
+
else yield fx.state.update(R.outboxRemove(item.id)); // row already gone from the store
|
|
116
|
+
}
|
|
117
|
+
if (rows.length === 0) continue;
|
|
118
|
+
|
|
119
|
+
const req = remoteBatch(rows, new Set(batch.filter((i) => i.inDoubt).map((i) => i.id)));
|
|
120
|
+
let results: StatementResult[];
|
|
121
|
+
try {
|
|
122
|
+
const raw = (yield fx.remote.query(req.sql, req.vars, env.pushTimeoutMs)) as unknown;
|
|
123
|
+
// A response without statement results is a transport fault: every
|
|
124
|
+
// row stays queued, in doubt (handled as `!r` below).
|
|
125
|
+
results = Array.isArray(raw) ? (raw as StatementResult[]) : [];
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (classifySyncError(error) === 'application') {
|
|
128
|
+
// The whole request was rejected before any statement ran: treat the
|
|
129
|
+
// head as rejected, keep the rest for the next round.
|
|
130
|
+
yield* rollback(env, rows[0], { message: error instanceof Error ? error.message : String(error), kind: 'application' });
|
|
131
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: false, error });
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
// No answer: the server may have committed any prefix of the batch.
|
|
135
|
+
const attempts = batch.find((i) => i.id === rows[0].id)!.attempts;
|
|
136
|
+
yield fx.state.update(R.compose(R.outboxMarkInDoubt(rows.map((row) => row.id)), R.outboxBumpAttempts(rows[0].id)));
|
|
137
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: false, error });
|
|
138
|
+
yield fx.timer.set('outbox', backoffMs(attempts), { type: 'Drain' });
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const now = (yield fx.now()) as number;
|
|
143
|
+
let cutAt: number | null = null;
|
|
144
|
+
for (let i = 0; i < rows.length; i++) {
|
|
145
|
+
const row = rows[i];
|
|
146
|
+
const r = results[i];
|
|
147
|
+
if (!r) {
|
|
148
|
+
// Statements after a transport-level cut: no answer says whether
|
|
149
|
+
// they ran, so they are in doubt.
|
|
150
|
+
yield fx.state.update(R.outboxMarkInDoubt(rows.slice(i).map((unanswered) => unanswered.id)));
|
|
151
|
+
cutAt = i;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
const err = ERR(r);
|
|
155
|
+
if (err === null || isRepeatedLogCreate(row, err)) {
|
|
156
|
+
const del = deletePendingRow(row.id);
|
|
157
|
+
try {
|
|
158
|
+
yield fx.local.query(del.sql, del.vars);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
yield fx.emit({ type: 'log', level: 'error', message: 'outbox row delete failed after a successful push', data: { id: row.id, error } });
|
|
161
|
+
}
|
|
162
|
+
yield fx.state.update(R.outboxAck(row.id, now));
|
|
163
|
+
yield fx.emit({ type: 'mutation:settled', mutationId: row.id, recordId: row.recordId, eventType: row.mutationType });
|
|
164
|
+
yield fx.emit({ type: 'tabs:broadcast', message: { type: 'mutation-settled', mutationId: row.id, recordId: row.recordId, eventType: row.mutationType } });
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// An earlier statement in this batch was rejected (or was a repeated
|
|
168
|
+
// log row), so this one never ran: the next round sends it again.
|
|
169
|
+
if (err.includes(BATCH_SKIPPED)) break;
|
|
170
|
+
if (classifySyncError(new Error(err)) === 'network') {
|
|
171
|
+
cutAt = i;
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
yield* rollback(env, row, { message: err, kind: 'application' });
|
|
175
|
+
}
|
|
176
|
+
yield fx.timer.set('ack-prune', ACK_GRACE_MS, { type: 'AckPrune' });
|
|
177
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: cutAt === null, error: cutAt === null ? undefined : 'push interrupted' });
|
|
178
|
+
if (cutAt !== null) {
|
|
179
|
+
const cut = rows[cutAt];
|
|
180
|
+
const attempts = batch.find((i) => i.id === cut.id)!.attempts;
|
|
181
|
+
yield fx.state.update(R.outboxBumpAttempts(cut.id));
|
|
182
|
+
yield fx.timer.set('outbox', backoffMs(attempts), { type: 'Drain' });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Undo one rejected mutation. Order matters: the tray row is written and the
|
|
190
|
+
* pending row deleted in ONE transaction before any local revert, so a crash
|
|
191
|
+
* mid-way leaves the mutation in the tray, never silently re-applied.
|
|
192
|
+
*/
|
|
193
|
+
export function* rollback(
|
|
194
|
+
env: SagaEnv,
|
|
195
|
+
row: PendingMutationRow,
|
|
196
|
+
error: { message: string; kind: 'application' | 'unreplayable' }
|
|
197
|
+
): Saga<void> {
|
|
198
|
+
const attempts = ((yield fx.state.read((s) => s.outbox.find((i) => i.id === row.id)?.attempts)) as number | undefined) ?? 0;
|
|
199
|
+
const now = (yield fx.now()) as number;
|
|
200
|
+
let before: Record<string, unknown> | null = row.beforeRecord ?? null;
|
|
201
|
+
if (row.beforeRecord === undefined && row.mutationType !== 'create') {
|
|
202
|
+
// Legacy row: nothing captured locally, ask the server for the row.
|
|
203
|
+
try {
|
|
204
|
+
const res = (yield fx.remote.query('SELECT * FROM ONLY $id', { id: parseStoredRecordId(row.recordId) }, env.remoteTimeoutMs)) as StatementResult[];
|
|
205
|
+
const r = res?.[0];
|
|
206
|
+
before = r && r.status === 'OK' && r.result && typeof r.result === 'object' ? (r.result as Record<string, unknown>) : null;
|
|
207
|
+
} catch {
|
|
208
|
+
before = null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const plan = planRevert(row, before);
|
|
212
|
+
const failed = buildFailedRow(row, error, before, attempts, now, plan.revert);
|
|
213
|
+
const move = moveToFailedTx(failed);
|
|
214
|
+
try {
|
|
215
|
+
yield fx.local.execute(move.query, move.vars);
|
|
216
|
+
} catch (err) {
|
|
217
|
+
yield fx.emit({ type: 'log', level: 'error', message: 'failed to move a rejected mutation to the tray', data: { id: row.id, err } });
|
|
218
|
+
}
|
|
219
|
+
yield fx.state.update(R.compose(R.outboxRemove(row.id), R.setFailedCount((yield fx.state.read((s) => s.failedCount)) as number + 1)));
|
|
220
|
+
if (plan.tx) {
|
|
221
|
+
try {
|
|
222
|
+
yield fx.local.execute(plan.tx.query, plan.tx.vars);
|
|
223
|
+
} catch (err) {
|
|
224
|
+
yield fx.emit({ type: 'log', level: 'error', message: 'local revert failed', data: { id: row.id, err } });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
yield fx.ssp.ingest([plan.circuit]);
|
|
229
|
+
} catch (err) {
|
|
230
|
+
yield fx.emit({ type: 'log', level: 'warn', message: 'circuit revert failed', data: { id: row.id, err } });
|
|
231
|
+
}
|
|
232
|
+
const roleNow = (yield fx.state.read((s) => s.tabRole)) as ClientState['tabRole'];
|
|
233
|
+
if (roleNow !== 'solo') yield fx.emit({ type: 'tabs:broadcast', message: { type: 'ingest', records: [plan.circuit] } });
|
|
234
|
+
if (plan.circuit.op === 'DELETE') yield fx.state.update(R.deleteVersions([row.recordId]));
|
|
235
|
+
else if (before && typeof before._00_rv === 'number') yield fx.state.update(R.setVersions([[row.recordId, before._00_rv]]));
|
|
236
|
+
yield fx.state.update(R.markTableDirty(row.tableName));
|
|
237
|
+
const rolledBack = { type: 'mutation-rolled-back', mutationId: row.id, recordId: row.recordId, eventType: row.mutationType, error: error.message };
|
|
238
|
+
yield fx.emit({ type: 'mutation:rolled-back', mutationId: row.id, recordId: row.recordId, eventType: row.mutationType, error: error.message });
|
|
239
|
+
const [tabId, role] = (yield fx.state.read((s) => [s.tabId, s.tabRole])) as [string, ClientState['tabRole']];
|
|
240
|
+
const owner = mutationOwnerTabId(row.id);
|
|
241
|
+
if (role === 'leader' && owner && owner !== tabId) yield fx.emit({ type: 'tabs:sendTo', tabId: owner, message: rolledBack });
|
|
242
|
+
const count = (yield fx.state.read((s) => s.failedCount)) as number;
|
|
243
|
+
yield fx.emit({ type: 'tray:changed', count });
|
|
244
|
+
if (role === 'leader') yield fx.emit({ type: 'tabs:broadcast', message: { type: 'failed-mutations-changed', count } });
|
|
245
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { RecordId } from 'surrealdb';
|
|
3
|
+
import * as rows from './rows';
|
|
4
|
+
|
|
5
|
+
const rid = (t: string, i: string) => new RecordId(t, i);
|
|
6
|
+
|
|
7
|
+
describe('stored ids', () => {
|
|
8
|
+
it('strips ⟨⟩ escaping and reads the timestamp prefix', () => {
|
|
9
|
+
expect(rows.parseStoredRecordId('_00_pending_mutations:⟨1700000000000_0001_tab⟩')).toEqual(
|
|
10
|
+
rid('_00_pending_mutations', '1700000000000_0001_tab')
|
|
11
|
+
);
|
|
12
|
+
expect(rows.storedIdString(rid('_00_pending_mutations', 'x'))).toBe('_00_pending_mutations:x');
|
|
13
|
+
expect(rows.storedIdString('_00_pending_mutations:⟨x⟩')).toBe('_00_pending_mutations:x');
|
|
14
|
+
expect(rows.createdAtFromId('_00_pending_mutations:⟨1700000000000_0001_tab⟩')).toBe(1700000000000);
|
|
15
|
+
expect(rows.createdAtFromId('1700000000000_0001_tab')).toBe(1700000000000);
|
|
16
|
+
expect(rows.createdAtFromId('_00_pending_mutations:abc')).toBeNull();
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
describe('parsePendingRow', () => {
|
|
21
|
+
it('reads v2 rows', () => {
|
|
22
|
+
const row = rows.parsePendingRow({
|
|
23
|
+
id: '_00_pending_mutations:⟨1700000000000_0001_tab⟩',
|
|
24
|
+
mutationType: 'update',
|
|
25
|
+
recordId: 'thing:1',
|
|
26
|
+
tableName: 'thing',
|
|
27
|
+
data: { a: 1 },
|
|
28
|
+
beforeRecord: { id: 'thing:1', a: 0 },
|
|
29
|
+
createdAt: 5,
|
|
30
|
+
v: 2,
|
|
31
|
+
});
|
|
32
|
+
expect(row).toEqual({
|
|
33
|
+
id: '_00_pending_mutations:1700000000000_0001_tab',
|
|
34
|
+
mutationType: 'update',
|
|
35
|
+
recordId: 'thing:1',
|
|
36
|
+
tableName: 'thing',
|
|
37
|
+
data: { a: 1 },
|
|
38
|
+
beforeRecord: { id: 'thing:1', a: 0 },
|
|
39
|
+
createdAt: 5,
|
|
40
|
+
v: 2,
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
it('tolerates legacy rows and rejects unreplayable ones', () => {
|
|
44
|
+
const legacy = rows.parsePendingRow({
|
|
45
|
+
id: '_00_pending_mutations:1700000000000_0001_tab',
|
|
46
|
+
mutationType: 'delete',
|
|
47
|
+
recordId: rid('thing', '1'),
|
|
48
|
+
});
|
|
49
|
+
expect(legacy).toMatchObject({ tableName: 'thing', createdAt: 1700000000000, v: 1, beforeRecord: undefined });
|
|
50
|
+
expect(rows.parsePendingRow({ id: '_00_pending_mutations:1', mutationType: 'create', recordId: 'thing:1' })).toBeNull();
|
|
51
|
+
expect(rows.parsePendingRow({ id: '_00_pending_mutations:abc', mutationType: 'delete', recordId: 'thing:1' })!.createdAt).toBe(0);
|
|
52
|
+
expect(rows.parsePendingRow(null)).toBeNull();
|
|
53
|
+
expect(rows.parsePendingRow({ mutationType: 'bogus', recordId: 'x' })).toBeNull();
|
|
54
|
+
expect(rows.parsePendingRow({ mutationType: 'delete', recordId: 5 })).toBeNull();
|
|
55
|
+
expect(rows.toOutboxItem(legacy!)).toEqual({
|
|
56
|
+
id: legacy!.id,
|
|
57
|
+
type: 'delete',
|
|
58
|
+
recordId: 'thing:1',
|
|
59
|
+
table: 'thing',
|
|
60
|
+
status: 'pending',
|
|
61
|
+
ackedAt: null,
|
|
62
|
+
attempts: 0,
|
|
63
|
+
// A row read back from the store may have been sent by a session that died.
|
|
64
|
+
inDoubt: true,
|
|
65
|
+
});
|
|
66
|
+
expect(rows.loadPendingRows()).toBe('SELECT * FROM _00_pending_mutations ORDER BY id ASC');
|
|
67
|
+
expect(rows.loadFailedRows()).toBe('SELECT * FROM _00_failed_mutations ORDER BY failedAt ASC');
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('local write transactions', () => {
|
|
72
|
+
const base = { recordId: rid('thing', '1'), mutationId: rid('_00_pending_mutations', 'm'), table: 'thing', now: 7 };
|
|
73
|
+
it('create: row + v2 outbox entry, result index 0', () => {
|
|
74
|
+
const { query, vars } = rows.planCreateTx({ ...base, data: { a: 1, b: 'x' } });
|
|
75
|
+
expect(query.sql).toBe(
|
|
76
|
+
"BEGIN TRANSACTION;\nCREATE ONLY $id SET a = $data_a, b = $data_b;CREATE ONLY $mid SET mutationType = 'create', recordId = $id, tableName = $table, createdAt = $createdAt, v = 2, data = $data;\nCOMMIT TRANSACTION;"
|
|
77
|
+
);
|
|
78
|
+
expect(vars).toEqual({ id: base.recordId, mid: base.mutationId, table: 'thing', createdAt: 7, data: { a: 1, b: 'x' }, data_a: 1, data_b: 'x' });
|
|
79
|
+
expect(query.extract([null, 'row', 'outbox'])).toBe('row');
|
|
80
|
+
expect(rows.planCreateTx(base).vars.data).toEqual({});
|
|
81
|
+
});
|
|
82
|
+
it('update: rv bump, merge, outbox with beforeRecord, RETURN target', () => {
|
|
83
|
+
const { query, vars } = rows.planUpdateTx({ ...base, data: { a: 2 }, before: { id: 'thing:1', a: 1 } });
|
|
84
|
+
expect(query.sql).toContain('UPDATE $id SET _00_rv += 1;LET $updated = (UPDATE ONLY $id MERGE $data);');
|
|
85
|
+
expect(query.sql).toContain("mutationType = 'update', recordId = $id, tableName = $table, createdAt = $createdAt, v = 2, data = $data, beforeRecord = $before;RETURN {target: $updated}");
|
|
86
|
+
expect(vars.before).toEqual({ id: 'thing:1', a: 1 });
|
|
87
|
+
expect(rows.planUpdateTx(base).vars).toMatchObject({ data: {}, before: null });
|
|
88
|
+
});
|
|
89
|
+
it('delete: DELETE + outbox with beforeRecord', () => {
|
|
90
|
+
const { query, vars } = rows.planDeleteTx({ ...base, before: { id: 'thing:1' } });
|
|
91
|
+
expect(query.sql).toBe(
|
|
92
|
+
"BEGIN TRANSACTION;\nDELETE $id;CREATE ONLY $mid SET mutationType = 'delete', recordId = $id, tableName = $table, createdAt = $createdAt, v = 2, beforeRecord = $before;\nCOMMIT TRANSACTION;"
|
|
93
|
+
);
|
|
94
|
+
expect(vars.before).toEqual({ id: 'thing:1' });
|
|
95
|
+
expect(rows.planDeleteTx(base).vars.before).toBeNull();
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
describe('debounced update transactions', () => {
|
|
100
|
+
it('local-only update and deferred outbox row', () => {
|
|
101
|
+
const local = rows.planLocalOnlyUpdateTx({ recordId: rid('thing', '1'), data: { a: 1 } });
|
|
102
|
+
expect(local.query.sql).toBe('BEGIN TRANSACTION;\nUPDATE $id SET _00_rv += 1;LET $updated = (UPDATE ONLY $id MERGE $data);RETURN {target: $updated};\nCOMMIT TRANSACTION;');
|
|
103
|
+
expect(local.query.extract([null, 1, 2, { target: 'x' }])).toEqual({ target: 'x' });
|
|
104
|
+
const deferred = rows.planDeferredOutboxRowTx({ recordId: rid('thing', '1'), mutationId: rid('_00_pending_mutations', 'm'), table: 'thing', data: { a: 1 }, before: { a: 0 }, now: 3 });
|
|
105
|
+
expect(deferred.query.sql).toBe("BEGIN TRANSACTION;\nCREATE ONLY $mid SET mutationType = 'update', recordId = $id, tableName = $table, createdAt = $createdAt, v = 2, data = $data, beforeRecord = $before;\nCOMMIT TRANSACTION;");
|
|
106
|
+
expect(rows.planDeferredOutboxRowTx({ recordId: rid('thing', '1'), mutationId: rid('_00_pending_mutations', 'm'), table: 'thing', now: 3 }).vars).toMatchObject({ data: {}, before: null });
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('with a mirror: the patch is upserted beside the row, and the flush moves it in one transaction', () => {
|
|
110
|
+
const wrow = { recordId: rid('thing', '1'), tableName: 'thing', data: { a: 1, b: 2 }, beforeRecord: null, flushBy: 9 };
|
|
111
|
+
const local = rows.planLocalOnlyUpdateTx({ recordId: rid('thing', '1'), data: { b: 2 }, mirror: { id: rid('_00_pending_writes', 'w'), row: wrow } });
|
|
112
|
+
expect(local.query.sql).toBe(
|
|
113
|
+
'BEGIN TRANSACTION;\nUPDATE $id SET _00_rv += 1;LET $updated = (UPDATE ONLY $id MERGE $data);UPSERT ONLY $wid REPLACE $wrow;RETURN {target: $updated};\nCOMMIT TRANSACTION;'
|
|
114
|
+
);
|
|
115
|
+
expect(local.vars).toEqual({ id: rid('thing', '1'), data: { b: 2 }, wid: rid('_00_pending_writes', 'w'), wrow });
|
|
116
|
+
expect(local.query.extract([null, 1, 2, 3, { target: 'x' }])).toEqual({ target: 'x' });
|
|
117
|
+
const moved = rows.planDeferredOutboxRowTx({ recordId: rid('thing', '1'), mutationId: rid('_00_pending_mutations', 'm'), table: 'thing', data: { a: 1 }, now: 3, mirrorId: rid('_00_pending_writes', 'w') });
|
|
118
|
+
expect(moved.query.sql).toContain('beforeRecord = $before;DELETE $wid;\nCOMMIT');
|
|
119
|
+
expect(moved.vars.wid).toEqual(rid('_00_pending_writes', 'w'));
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('pending write ids and rows', () => {
|
|
123
|
+
expect(rows.pendingWriteId('_00_pending_mutations:0000000000001_0001_tab')).toBe('_00_pending_writes:0000000000001_0001_tab');
|
|
124
|
+
expect(rows.pendingWriteId('mutation-1')).toBe('_00_pending_writes:mutation-1');
|
|
125
|
+
expect(rows.parsePendingWriteRow({ id: '_00_pending_writes:⟨w-1⟩', recordId: rid('thing', '1'), data: { a: 1 }, beforeRecord: { a: 0 }, flushBy: 5 })).toEqual({
|
|
126
|
+
id: '_00_pending_writes:w-1',
|
|
127
|
+
recordId: 'thing:1',
|
|
128
|
+
tableName: 'thing',
|
|
129
|
+
data: { a: 1 },
|
|
130
|
+
beforeRecord: { a: 0 },
|
|
131
|
+
flushBy: 5,
|
|
132
|
+
});
|
|
133
|
+
expect(rows.parsePendingWriteRow({ id: 'w', recordId: 'thing:1', tableName: 'thing', data: {} })).toMatchObject({ beforeRecord: null, flushBy: 0 });
|
|
134
|
+
expect(rows.parsePendingWriteRow({ id: 'w', recordId: 'thing:1' })).toBeNull();
|
|
135
|
+
expect(rows.parsePendingWriteRow({ id: 'w', data: {} })).toBeNull();
|
|
136
|
+
expect(rows.parsePendingWriteRow('junk')).toBeNull();
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe('remoteBatch', () => {
|
|
141
|
+
it('one statement per row, indexed vars, mixed types', () => {
|
|
142
|
+
const { sql, vars } = rows.remoteBatch([
|
|
143
|
+
{ id: 'm1', mutationType: 'create', recordId: 'thing:1', tableName: 'thing', data: { a: 1 }, createdAt: 0, v: 2 },
|
|
144
|
+
{ id: 'm2', mutationType: 'update', recordId: 'thing:2', tableName: 'thing', data: { b: 2 }, createdAt: 0, v: 2 },
|
|
145
|
+
{ id: 'm3', mutationType: 'delete', recordId: 'thing:3', tableName: 'thing', createdAt: 0, v: 2 },
|
|
146
|
+
{ id: 'm4', mutationType: 'update', recordId: 'thing:4', tableName: 'thing', createdAt: 0, v: 2 },
|
|
147
|
+
]);
|
|
148
|
+
// Chained: each statement runs only if the one before it committed.
|
|
149
|
+
const skip = `IF !$ok0 { THROW "${rows.BATCH_SKIPPED}" }; `;
|
|
150
|
+
expect(sql.split(';\n')).toEqual([
|
|
151
|
+
'LET $ok0 = { CREATE ONLY $id0 SET a = $d0_a; true }',
|
|
152
|
+
`LET $ok1 = { ${skip}UPDATE $id1 MERGE $data1; true }`,
|
|
153
|
+
`LET $ok2 = { ${skip.replace('$ok0', '$ok1')}DELETE $id2; true }`,
|
|
154
|
+
`LET $ok3 = { ${skip.replace('$ok0', '$ok2')}UPDATE $id3 MERGE $data3; true }`,
|
|
155
|
+
]);
|
|
156
|
+
expect(vars).toEqual({
|
|
157
|
+
id0: rid('thing', '1'),
|
|
158
|
+
d0_a: 1,
|
|
159
|
+
id1: rid('thing', '2'),
|
|
160
|
+
data1: { b: 2 },
|
|
161
|
+
id2: rid('thing', '3'),
|
|
162
|
+
id3: rid('thing', '4'),
|
|
163
|
+
data3: {},
|
|
164
|
+
});
|
|
165
|
+
expect(rows.remoteBatch([{ id: 'm', mutationType: 'create', recordId: 'thing:9', tableName: 'thing', createdAt: 0, v: 2 }]).sql).toBe('LET $ok0 = { CREATE ONLY $id0 SET ; true }');
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('an in-doubt CREATE is a no-op when the server row matches every field no later in-doubt row of it may have changed', () => {
|
|
169
|
+
const row = (id: string, mutationType: rows.PendingMutationRow['mutationType'], recordId: string, data?: Record<string, unknown>): rows.PendingMutationRow => ({
|
|
170
|
+
id,
|
|
171
|
+
mutationType,
|
|
172
|
+
recordId,
|
|
173
|
+
tableName: recordId.split(':')[0],
|
|
174
|
+
data,
|
|
175
|
+
createdAt: 0,
|
|
176
|
+
v: 2,
|
|
177
|
+
});
|
|
178
|
+
const was = (i: number, ...keys: string[]) =>
|
|
179
|
+
`LET $was${i} = (SELECT * FROM ONLY $id${i}); IF ${[`($was${i} = NONE)`, ...keys.map((k) => `($was${i}.${k} != $d${i}_${k})`)].join(' OR ')} { CREATE ONLY $id${i} SET ${['a', 'b']
|
|
180
|
+
.map((k) => `${k} = $d${i}_${k}`)
|
|
181
|
+
.join(', ')} }`;
|
|
182
|
+
const statement = (sql: string, i: number) => sql.split(';\n')[i].replace(/^LET \$ok\d+ = \{ (IF !\$ok\d+ \{ THROW "[^"]+" \}; )?/, '').replace(/; true \}$/, '');
|
|
183
|
+
const batch = [
|
|
184
|
+
row('m1', 'create', 'thing:1', { a: 1, b: 1 }),
|
|
185
|
+
row('m2', 'update', 'thing:1', { b: 2 }),
|
|
186
|
+
row('m3', 'create', 'thing:2', { a: 1, b: 1 }),
|
|
187
|
+
row('m4', 'update', 'thing:2', { a: 2 }), // not in doubt: it never ran
|
|
188
|
+
row('m5', 'create', 'thing:3', { a: 1, b: 1 }),
|
|
189
|
+
row('m6', 'delete', 'thing:3'),
|
|
190
|
+
row('m7', 'create', 'thing:4', { a: 1, b: 1 }),
|
|
191
|
+
row('m8', 'update', 'thing:9', { a: 2 }), // another record
|
|
192
|
+
row('m9', 'update', 'thing:1'), // no payload: changes nothing
|
|
193
|
+
];
|
|
194
|
+
const { sql } = rows.remoteBatch(batch, new Set(['m1', 'm2', 'm3', 'm5', 'm6', 'm8', 'm9']));
|
|
195
|
+
expect(statement(sql, 0)).toBe(was(0, 'a')); // b may be m2's
|
|
196
|
+
expect(statement(sql, 2)).toBe(was(2, 'a', 'b'));
|
|
197
|
+
expect(statement(sql, 4)).toBe(was(4)); // m6 may have deleted it and something else re-created it
|
|
198
|
+
expect(statement(sql, 6)).toBe('CREATE ONLY $id6 SET a = $d6_a, b = $d6_b'); // not in doubt: strict
|
|
199
|
+
// A CRDT log row's id is fresh and the row immutable: existence is proof, in doubt or not.
|
|
200
|
+
expect(statement(rows.remoteBatch([row('l', 'create', 'doc__crdt_log:1', { a: 1, b: 1 })]).sql, 0)).toBe(was(0));
|
|
201
|
+
expect(statement(rows.remoteBatch([row('e', 'create', 'thing:5')], new Set(['e'])).sql, 0)).toBe(
|
|
202
|
+
'LET $was0 = (SELECT * FROM ONLY $id0); IF ($was0 = NONE) { CREATE ONLY $id0 SET }'
|
|
203
|
+
);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
describe('rollback plans', () => {
|
|
208
|
+
const pending = (type: rows.PendingMutationRow['mutationType']): rows.PendingMutationRow => ({
|
|
209
|
+
id: '_00_pending_mutations:m',
|
|
210
|
+
mutationType: type,
|
|
211
|
+
recordId: 'thing:1',
|
|
212
|
+
tableName: 'thing',
|
|
213
|
+
data: { a: 1 },
|
|
214
|
+
createdAt: 1,
|
|
215
|
+
v: 2,
|
|
216
|
+
});
|
|
217
|
+
it('create reverts by delete', () => {
|
|
218
|
+
const plan = rows.planRevert(pending('create'), null);
|
|
219
|
+
expect(plan.revert).toBe('full');
|
|
220
|
+
expect(plan.tx!.query.sql).toBe('BEGIN TRANSACTION;\nDELETE $id;\nCOMMIT TRANSACTION;');
|
|
221
|
+
expect(plan.circuit).toEqual({ table: 'thing', op: 'DELETE', id: 'thing:1', record: { a: 1 } });
|
|
222
|
+
expect(rows.planRevert({ ...pending('create'), data: undefined }, null).circuit.record).toEqual({});
|
|
223
|
+
});
|
|
224
|
+
it('update / delete restore beforeRecord, or are partial without it', () => {
|
|
225
|
+
const before = { id: 'thing:1', a: 0, _00_rv: 3 };
|
|
226
|
+
const upd = rows.planRevert(pending('update'), before);
|
|
227
|
+
expect(upd.tx!.query.sql).toBe('BEGIN TRANSACTION;\nUPSERT ONLY $id REPLACE $content;\nCOMMIT TRANSACTION;');
|
|
228
|
+
expect(upd.tx!.vars).toEqual({ id: rid('thing', '1'), content: { a: 0, _00_rv: 3 } });
|
|
229
|
+
expect(upd.circuit).toMatchObject({ op: 'UPDATE', record: { a: 0, _00_rv: 3, id: rid('thing', '1') } });
|
|
230
|
+
const del = rows.planRevert(pending('delete'), before);
|
|
231
|
+
expect(del.circuit.op).toBe('CREATE');
|
|
232
|
+
const partial = rows.planRevert(pending('update'), null);
|
|
233
|
+
expect(partial).toEqual({ tx: null, circuit: { table: 'thing', op: 'UPDATE', id: 'thing:1', record: {} }, revert: 'partial' });
|
|
234
|
+
});
|
|
235
|
+
it('failed rows: build, move tx, delete statements, parse', () => {
|
|
236
|
+
const failed = rows.buildFailedRow(pending('update'), { message: 'denied', kind: 'application' }, { id: 'thing:1' }, 2, 99, 'full');
|
|
237
|
+
expect(failed).toMatchObject({ id: '_00_pending_mutations:m', attempts: 2, failedAt: 99, revert: 'full', beforeRecord: { id: 'thing:1' } });
|
|
238
|
+
const { query, vars } = rows.moveToFailedTx(failed);
|
|
239
|
+
expect(query.sql).toBe('BEGIN TRANSACTION;\nCREATE ONLY $fid CONTENT $failed;DELETE $mid;\nCOMMIT TRANSACTION;');
|
|
240
|
+
expect(vars.fid).toEqual(rid('_00_failed_mutations', 'm'));
|
|
241
|
+
expect(vars.mid).toEqual(rid('_00_pending_mutations', 'm'));
|
|
242
|
+
expect((vars.failed as Record<string, unknown>).id).toBeUndefined();
|
|
243
|
+
expect(rows.deletePendingRow('_00_pending_mutations:m')).toEqual({ sql: 'DELETE $mid', vars: { mid: rid('_00_pending_mutations', 'm') } });
|
|
244
|
+
expect(rows.deleteFailedRow('_00_pending_mutations:m')).toEqual({ sql: 'DELETE $fid', vars: { fid: rid('_00_failed_mutations', 'm') } });
|
|
245
|
+
const parsed = rows.parseFailedRow({ ...failed, id: '_00_failed_mutations:⟨m⟩' });
|
|
246
|
+
expect(parsed).toMatchObject({ id: '_00_pending_mutations:m', mutationType: 'update', error: { message: 'denied', kind: 'application' }, revert: 'full' });
|
|
247
|
+
expect(rows.parseFailedRow({ id: '_00_failed_mutations:m', mutationType: 'delete', recordId: 'thing:2', error: { kind: 'unreplayable' }, revert: 'partial' })).toMatchObject({
|
|
248
|
+
tableName: 'thing',
|
|
249
|
+
error: { message: 'unknown', kind: 'unreplayable' },
|
|
250
|
+
attempts: 0,
|
|
251
|
+
createdAt: 0,
|
|
252
|
+
failedAt: 0,
|
|
253
|
+
revert: 'partial',
|
|
254
|
+
beforeRecord: null,
|
|
255
|
+
data: undefined,
|
|
256
|
+
});
|
|
257
|
+
expect(rows.parseFailedRow(null)).toBeNull();
|
|
258
|
+
expect(rows.parseFailedRow({ id: '_00_failed_mutations:m', mutationType: 'create', recordId: 'thing:1' })!.error).toEqual({ message: 'unknown', kind: 'application' });
|
|
259
|
+
expect(rows.parseFailedRow({ mutationType: 'nope', recordId: 'x' })).toBeNull();
|
|
260
|
+
expect(rows.parseFailedRow({ mutationType: 'delete', recordId: 1 })).toBeNull();
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe('hydrateRowData', () => {
|
|
265
|
+
const columns = { owner: { recordId: true }, at: { dateTime: true }, n: {} } as any;
|
|
266
|
+
const base: rows.PendingMutationRow = { id: 'm', mutationType: 'create', recordId: 'thing:1', tableName: 'thing', createdAt: 0, v: 2 };
|
|
267
|
+
it('re-types record and datetime fields from the schema, keeps unknown keys, leaves rows without data or schema alone', () => {
|
|
268
|
+
const out = rows.hydrateRowData({ ...base, data: { owner: 'user:u1', at: '2026-01-02T00:00:00.000Z', n: 1, extra: 'x' } }, columns);
|
|
269
|
+
expect(out.data).toEqual({ owner: rid('user', 'u1'), at: new Date('2026-01-02T00:00:00.000Z'), n: 1, extra: 'x' });
|
|
270
|
+
expect(rows.hydrateRowData(base, columns)).toBe(base);
|
|
271
|
+
const noSchema = { ...base, data: { owner: 'user:u1' } };
|
|
272
|
+
expect(rows.hydrateRowData(noSchema, null)).toBe(noSchema);
|
|
273
|
+
});
|
|
274
|
+
it('sends a payload the schema rejects as it is', () => {
|
|
275
|
+
const bad = { ...base, data: { owner: 42 } };
|
|
276
|
+
expect(rows.hydrateRowData(bad, columns)).toBe(bad);
|
|
277
|
+
});
|
|
278
|
+
});
|