@spooky-sync/core 0.0.1-canary.32 → 0.0.1-canary.321
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 +81 -0
- package/README.md +56 -16
- package/dist/index.d.ts +2034 -137
- package/dist/index.js +15236 -2467
- package/dist/live.d.ts +141 -0
- package/dist/live.js +733 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/otel/index.js +3 -3
- package/dist/pure.d.ts +365 -0
- package/dist/pure.js +24 -0
- package/dist/sqlite-open.js +379 -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 +472 -0
- package/dist/types.d.ts +1821 -38
- package/dist/worker-edges.js +470 -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 +27 -7
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +172 -0
- package/skills/sp00ky-core/SKILL.md +31 -6
- package/skills/sp00ky-core/references/config.md +6 -0
- package/src/boot/auth-flip.saga.test.ts +135 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +180 -0
- package/src/boot/boot.saga.ts +142 -0
- package/src/boot/bucket-switch.saga.test.ts +187 -0
- package/src/boot/bucket-switch.saga.ts +133 -0
- package/src/boot/preload.saga.test.ts +51 -0
- package/src/boot/preload.saga.ts +31 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/build-globals.d.ts +12 -0
- package/src/client/bucket-handle.test.ts +117 -0
- package/src/client/bucket-handle.ts +227 -0
- package/src/client/router.test.ts +58 -0
- package/src/client/router.ts +100 -0
- package/src/client/runtime.test.ts +195 -0
- package/src/client/runtime.ts +296 -0
- package/src/client/services.test.ts +60 -0
- package/src/client/services.ts +418 -0
- package/src/client/sp00ky-client.test.ts +303 -0
- package/src/client/sp00ky-client.ts +586 -0
- package/src/events/events.test.ts +2 -1
- package/src/events/index.ts +3 -0
- package/src/index.ts +69 -1
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +80 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +163 -0
- package/src/kernel/events.ts +57 -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 +501 -0
- package/src/live/index.ts +1039 -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 +169 -0
- package/src/modules/auth/events/index.ts +9 -2
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +205 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +466 -19
- package/src/modules/crdt/crdt-field.ts +294 -0
- package/src/modules/crdt/crdt-hydration.test.ts +210 -0
- package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
- package/src/modules/crdt/index.ts +463 -0
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +746 -95
- 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/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 +285 -0
- package/src/mutation/push.saga.ts +217 -0
- package/src/mutation/rows.test.ts +231 -0
- package/src/mutation/rows.ts +427 -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 +316 -0
- package/src/mutation/write.saga.ts +268 -0
- package/src/otel/index.ts +10 -7
- package/src/pure.ts +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +337 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +56 -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 +159 -0
- package/src/query/list-ref-live.integration.test.ts +203 -0
- package/src/query/materialize.saga.test.ts +115 -0
- package/src/query/materialize.saga.ts +84 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +57 -0
- package/src/query/membership.saga.test.ts +350 -0
- package/src/query/membership.saga.ts +278 -0
- package/src/query/membership.test.ts +118 -0
- package/src/query/membership.ts +201 -0
- package/src/query/register.saga.test.ts +311 -0
- package/src/query/register.saga.ts +229 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/sql.test.ts +112 -0
- package/src/query/sql.ts +149 -0
- package/src/query/window-query.test.ts +70 -0
- package/src/query/window-query.ts +195 -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 +199 -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 +146 -61
- package/src/services/database/engine-factory.ts +33 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/events/index.ts +2 -1
- 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 +59 -16
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +487 -63
- 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 +273 -6
- package/src/services/database/sqlite-cache-engine.test.ts +617 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1372 -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 +145 -0
- package/src/services/database/sqlite-plan-sql.ts +182 -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 +416 -0
- package/src/services/database/surreal-cache-engine.ts +161 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +189 -7
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +10 -3
- package/src/services/persistence/surrealdb.ts +4 -4
- package/src/services/stream-processor/index.ts +783 -68
- 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 +198 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +58 -2
- package/src/services/tabs/broker-client.ts +283 -0
- package/src/services/tabs/broker.test.ts +327 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +638 -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 +640 -0
- package/src/sp00ky.ts +5 -395
- package/src/state/client-state.ts +200 -0
- package/src/state/lifecycle.test.ts +141 -0
- package/src/state/lifecycle.ts +99 -0
- package/src/state/reducers.test.ts +304 -0
- package/src/state/reducers.ts +526 -0
- package/src/state/selectors.test.ts +175 -0
- package/src/state/selectors.ts +222 -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 +178 -0
- package/src/sync/live.saga.ts +107 -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 +133 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +48 -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 +624 -10
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +39 -0
- package/src/utils/error-classification.test.ts +54 -0
- package/src/utils/error-classification.ts +25 -0
- package/src/utils/index.ts +78 -12
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +64 -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 +30 -18
- 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 -879
- package/src/modules/sync/engine.ts +0 -173
- package/src/modules/sync/events/index.ts +0 -77
- 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 -89
- package/src/modules/sync/queue/queue-up.ts +0 -223
- package/src/modules/sync/scheduler.ts +0 -84
- package/src/modules/sync/sync.ts +0 -421
- package/src/modules/sync/utils.test.ts +0 -311
- package/src/modules/sync/utils.ts +0 -167
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { buildJobRecord } from './jobs';
|
|
3
|
+
|
|
4
|
+
const schema = {
|
|
5
|
+
tables: [],
|
|
6
|
+
backends: {
|
|
7
|
+
api: { outboxTable: '_00_job_api', routes: { hello: { args: { name: { optional: false }, tone: { optional: true } } } } },
|
|
8
|
+
bare: { routes: { x: { args: {} } } },
|
|
9
|
+
},
|
|
10
|
+
} as any;
|
|
11
|
+
|
|
12
|
+
describe('buildJobRecord', () => {
|
|
13
|
+
it('builds a pending job row with the route payload and option overrides', () => {
|
|
14
|
+
const { tableName, record } = buildJobRecord(schema, 'api', 'hello', { name: 'a', extra: 1 }, { max_retries: 5, retry_strategy: 'exponential', timeout: 9, delay: 100, assignedTo: 'w1' });
|
|
15
|
+
expect(tableName).toBe('_00_job_api');
|
|
16
|
+
expect(record).toEqual({ path: 'hello', payload: JSON.stringify({ name: 'a', tone: undefined }), status: 'pending', max_retries: 5, retry_strategy: 'exponential', timeout: 9, delay: 100, assigned_to: 'w1' });
|
|
17
|
+
expect(buildJobRecord(schema, 'api', 'hello', { name: 'a' }).record).toMatchObject({ max_retries: 3, retry_strategy: 'linear' });
|
|
18
|
+
});
|
|
19
|
+
it('rejects unknown routes, missing outbox tables and missing required args', () => {
|
|
20
|
+
expect(() => buildJobRecord(schema, 'api', 'nope', {})).toThrow('Route api.nope not found');
|
|
21
|
+
expect(() => buildJobRecord(schema, 'bare', 'x', {})).toThrow('Outbox table for backend bare not found');
|
|
22
|
+
expect(() => buildJobRecord(schema, 'api', 'hello', {})).toThrow('Missing required argument name');
|
|
23
|
+
expect(() => buildJobRecord({ tables: [] } as any, 'api', 'hello', {})).toThrow('Route api.hello not found');
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { RunOptions } from '../types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Build the outbox job record for a backend route and resolve its table.
|
|
6
|
+
* Every job is a single execution; recurring work is declared server-side.
|
|
7
|
+
*/
|
|
8
|
+
export function buildJobRecord(
|
|
9
|
+
schema: SchemaStructure,
|
|
10
|
+
backend: string,
|
|
11
|
+
path: string,
|
|
12
|
+
data: Record<string, unknown>,
|
|
13
|
+
options?: RunOptions
|
|
14
|
+
): { tableName: string; record: Record<string, unknown> } {
|
|
15
|
+
const backends = (schema as { backends?: Record<string, { outboxTable?: string; routes?: Record<string, { args: Record<string, { optional: boolean }> }> }> }).backends;
|
|
16
|
+
const route = backends?.[backend]?.routes?.[path];
|
|
17
|
+
if (!route) throw new Error(`Route ${backend}.${path} not found`);
|
|
18
|
+
const tableName = backends?.[backend]?.outboxTable;
|
|
19
|
+
if (!tableName) throw new Error(`Outbox table for backend ${backend} not found`);
|
|
20
|
+
|
|
21
|
+
const payload: Record<string, unknown> = {};
|
|
22
|
+
for (const argName of Object.keys(route.args)) {
|
|
23
|
+
const arg = route.args[argName];
|
|
24
|
+
if (data[argName] === undefined && arg.optional === false) throw new Error(`Missing required argument ${argName}`);
|
|
25
|
+
payload[argName] = data[argName];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const record: Record<string, unknown> = {
|
|
29
|
+
path,
|
|
30
|
+
payload: JSON.stringify(payload),
|
|
31
|
+
// Explicit: the schema's server-side DEFAULT does not apply to an
|
|
32
|
+
// optimistic local create, and in-flight indicators key on `pending`.
|
|
33
|
+
status: 'pending',
|
|
34
|
+
max_retries: options?.max_retries ?? 3,
|
|
35
|
+
retry_strategy: options?.retry_strategy ?? 'linear',
|
|
36
|
+
};
|
|
37
|
+
if (options?.timeout != null) record.timeout = options.timeout;
|
|
38
|
+
if (options?.delay != null) record.delay = options.delay;
|
|
39
|
+
if (options?.assignedTo) record.assigned_to = options.assignedTo;
|
|
40
|
+
return { tableName, record };
|
|
41
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { mintMutationId, mutationOwnerTabId } from './mutation-id';
|
|
3
|
+
|
|
4
|
+
describe('mutationOwnerTabId (raw ids)', () => {
|
|
5
|
+
it('mints with the fallback tab id when none is given', () => {
|
|
6
|
+
const id = mintMutationId();
|
|
7
|
+
expect(id.startsWith('_00_pending_mutations:')).toBe(true);
|
|
8
|
+
expect(mutationOwnerTabId(id)).toMatch(/^[a-z0-9]+$/);
|
|
9
|
+
});
|
|
10
|
+
it('accepts an id without the table prefix', () => {
|
|
11
|
+
expect(mutationOwnerTabId('1700000000000_0001_tab9')).toBe('tab9');
|
|
12
|
+
expect(mutationOwnerTabId('1700000000000')).toBeNull();
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// The old `_00_pending_mutations:${Date.now()}` collided within a millisecond
|
|
17
|
+
// (guaranteed once multiple tabs share a store) and never actually ordered the
|
|
18
|
+
// drain. These pin the new id's three properties: unique, sortable, routable.
|
|
19
|
+
describe('mutation ids', () => {
|
|
20
|
+
it('never collides within a burst', () => {
|
|
21
|
+
const ids = new Set(Array.from({ length: 1000 }, () => mintMutationId('tabx')));
|
|
22
|
+
expect(ids.size).toBe(1000);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('sorts lexicographically in mint order (ORDER BY id is chronological)', () => {
|
|
26
|
+
const ids = Array.from({ length: 200 }, () => mintMutationId('tabx'));
|
|
27
|
+
expect([...ids].sort()).toEqual(ids);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('routes back to the owning tab', () => {
|
|
31
|
+
expect(mutationOwnerTabId(mintMutationId('tab-abc'))).toBe('tab-abc');
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('returns null for a legacy numeric id instead of misrouting', () => {
|
|
35
|
+
expect(mutationOwnerTabId('_00_pending_mutations:1753875000000')).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbox mutation ids. Previously `_00_pending_mutations:${Date.now()}`, which
|
|
3
|
+
* (a) collides when two mutations land in the same millisecond, a real case
|
|
4
|
+
* once multiple tabs share one store, and (b) never actually ordered the
|
|
5
|
+
* drain, because `loadFromDatabase` sorted by a `created_at` field that does
|
|
6
|
+
* not exist on the table. The new shape is sortable AND collision-free:
|
|
7
|
+
*
|
|
8
|
+
* <13-digit zero-padded ms timestamp>_<4-digit base36 seq>_<tabId>
|
|
9
|
+
*
|
|
10
|
+
* Lexicographic order == chronological order (per tab; cross-tab within-ms
|
|
11
|
+
* ordering is arbitrary, which matches reality), so `ORDER BY id` in the
|
|
12
|
+
* drain is now meaningful. The tabId suffix also routes rollbacks back to the
|
|
13
|
+
* tab that owns the mutation in shared-tabs mode.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
let seq = 0;
|
|
17
|
+
|
|
18
|
+
/** Tab identity for mutation ids in SOLO mode, minted once per session. In
|
|
19
|
+
* shared-tabs mode the coordinator's tabId is passed in instead. */
|
|
20
|
+
const FALLBACK_TAB_ID = Math.random().toString(36).slice(2, 8);
|
|
21
|
+
|
|
22
|
+
export function mintMutationId(tabId?: string): string {
|
|
23
|
+
const ts = Date.now().toString().padStart(13, '0');
|
|
24
|
+
const n = (seq = (seq + 1) % 36 ** 4).toString(36).padStart(4, '0');
|
|
25
|
+
return `_00_pending_mutations:${ts}_${n}_${tabId ?? FALLBACK_TAB_ID}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The tab that created the mutation, or null for a legacy numeric id. */
|
|
29
|
+
export function mutationOwnerTabId(mutationId: string): string | null {
|
|
30
|
+
const raw = mutationId.startsWith('_00_pending_mutations:')
|
|
31
|
+
? mutationId.slice('_00_pending_mutations:'.length)
|
|
32
|
+
: mutationId;
|
|
33
|
+
const parts = raw.split('_');
|
|
34
|
+
return parts.length >= 3 ? parts[parts.length - 1] : null;
|
|
35
|
+
}
|
|
@@ -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,285 @@
|
|
|
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 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
|
+
const pendingRow = (n: number, type: PendingMutationRow['mutationType'] = 'create', extra: Partial<PendingMutationRow> = {}) => ({
|
|
15
|
+
id: `_00_pending_mutations:m${n}`,
|
|
16
|
+
mutationType: type,
|
|
17
|
+
recordId: `thing:${n}`,
|
|
18
|
+
tableName: 'thing',
|
|
19
|
+
data: type === 'delete' ? undefined : { a: n },
|
|
20
|
+
beforeRecord: type === 'create' ? undefined : { id: `thing:${n}`, a: 0, _00_rv: 7 },
|
|
21
|
+
createdAt: 1,
|
|
22
|
+
v: 2,
|
|
23
|
+
...extra,
|
|
24
|
+
});
|
|
25
|
+
const items = (...ns: number[]) => ns.map((n) => buildOutboxItem({ id: `_00_pending_mutations:m${n}`, recordId: `thing:${n}`, type: 'create' }));
|
|
26
|
+
const stateWith = (rows: number[], ...extra: Parameters<typeof buildState>[1][]) =>
|
|
27
|
+
buildState([buildEntry({ def: { hash: 'q', tableName: 'thing' } })], R.outboxReplace(items(...rows)), ...extra);
|
|
28
|
+
|
|
29
|
+
describe('drain', () => {
|
|
30
|
+
it('re-types stored payloads from the schema before pushing (a stored record field is a string)', async () => {
|
|
31
|
+
const typedEnv = defaultEnv({ tables: [{ name: 'thing', columns: { owner: { recordId: true } } }] } as any, { outboxBatchSize: 2 });
|
|
32
|
+
let vars: any = null;
|
|
33
|
+
await runPure(drain(typedEnv), {
|
|
34
|
+
state: stateWith([1]),
|
|
35
|
+
handlers: {
|
|
36
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [[pendingRow(1, 'create', { data: { owner: 'user:u1' } })]] : []),
|
|
37
|
+
'remote.query': (e: any) => ((vars = e.vars), [ok()]),
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
expect(vars.d0_owner).toEqual(new RecordId('user', 'u1'));
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('pushes batches in FIFO order, acks each accepted row, deletes its pending row, then loops', async () => {
|
|
44
|
+
const pushed: string[] = [];
|
|
45
|
+
const out = await runPure(drain(env), {
|
|
46
|
+
state: stateWith([1, 2, 3]),
|
|
47
|
+
now: 500,
|
|
48
|
+
handlers: {
|
|
49
|
+
'local.query': (e: any) => {
|
|
50
|
+
if (e.sql === 'SELECT * FROM $ids') return [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))];
|
|
51
|
+
return [];
|
|
52
|
+
},
|
|
53
|
+
'remote.query': (e: any) => {
|
|
54
|
+
pushed.push(e.sql);
|
|
55
|
+
return e.sql.split(';\n').map(() => ok());
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
expect(pushed).toEqual(['CREATE ONLY $id0 SET a = $d0_a;\nCREATE ONLY $id1 SET a = $d1_a', 'CREATE ONLY $id0 SET a = $d0_a']);
|
|
60
|
+
expect(out.state.outbox.every((i) => i.status === 'acked' && i.ackedAt === 500)).toBe(true);
|
|
61
|
+
expect(out.log.filter((e) => e.kind === 'local.query' && (e as any).sql === 'DELETE $mid')).toHaveLength(3);
|
|
62
|
+
expect(out.emitted.filter((e) => e.type === 'mutation:settled')).toHaveLength(3);
|
|
63
|
+
expect(out.timers.get('ack-prune')).toEqual({ ms: 30_000, event: { type: 'AckPrune' } });
|
|
64
|
+
expect(out.dispatched.filter((d) => d.type === 'SyncOutcome')).toEqual([{ type: 'SyncOutcome', ok: true, error: undefined }, { type: 'SyncOutcome', ok: true, error: undefined }]);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('a rejected statement rolls back only that row; the rest of the batch is acked', async () => {
|
|
68
|
+
const out = await runPure(drain(env), {
|
|
69
|
+
state: stateWith([1, 2]),
|
|
70
|
+
handlers: {
|
|
71
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [[pendingRow(1), pendingRow(2)]] : []),
|
|
72
|
+
'remote.query': () => [err('permission denied'), ok()],
|
|
73
|
+
'local.execute': () => undefined,
|
|
74
|
+
'ssp.ingest': () => undefined,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
expect(out.state.outbox.map((i) => [i.id, i.status])).toEqual([['_00_pending_mutations:m2', 'acked']]);
|
|
78
|
+
expect(out.state.failedCount).toBe(1);
|
|
79
|
+
expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '_00_pending_mutations:m1', error: 'permission denied' }));
|
|
80
|
+
expect(out.dispatched.at(-1)).toEqual({ type: 'SyncOutcome', ok: true, error: undefined });
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('transport failures keep the tail queued behind a backoff timer (thrown, or a network ERR mid-batch, or a short result list)', async () => {
|
|
84
|
+
const thrown = await runPure(drain(env), {
|
|
85
|
+
state: stateWith([1, 2]),
|
|
86
|
+
handlers: {
|
|
87
|
+
'local.query': () => [[pendingRow(1), pendingRow(2)]],
|
|
88
|
+
'remote.query': () => {
|
|
89
|
+
throw new Error('socket closed');
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
expect(thrown.state.outbox.map((i) => i.status)).toEqual(['pending', 'pending']);
|
|
94
|
+
expect(thrown.state.outbox[0].attempts).toBe(1);
|
|
95
|
+
expect(thrown.timers.get('outbox')).toEqual({ ms: 500, event: { type: 'Drain' } });
|
|
96
|
+
expect(thrown.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('socket closed') }]);
|
|
97
|
+
const mid = await runPure(drain(env), {
|
|
98
|
+
state: stateWith([1, 2]),
|
|
99
|
+
handlers: { 'local.query': () => [[pendingRow(1), pendingRow(2)]], 'remote.query': () => [ok(), err('connection reset')] },
|
|
100
|
+
});
|
|
101
|
+
expect(mid.state.outbox.map((i) => [i.status, i.attempts])).toEqual([['acked', 0], ['pending', 1]]);
|
|
102
|
+
expect(mid.timers.get('outbox')!.ms).toBe(500);
|
|
103
|
+
const short = await runPure(drain(env), {
|
|
104
|
+
state: stateWith([1, 2]),
|
|
105
|
+
handlers: { 'local.query': () => [[pendingRow(1), pendingRow(2)]], 'remote.query': () => [ok()] },
|
|
106
|
+
});
|
|
107
|
+
expect(short.state.outbox.map((i) => i.status)).toEqual(['acked', 'pending']);
|
|
108
|
+
const undefinedRows = await runPure(drain(env), { state: stateWith([1]), handlers: { 'local.query': () => undefined } });
|
|
109
|
+
expect(undefinedRows.state.outbox).toEqual([]);
|
|
110
|
+
const notArray = await runPure(drain(env), {
|
|
111
|
+
state: stateWith([1]),
|
|
112
|
+
handlers: { 'local.query': () => [[pendingRow(1)]], 'remote.query': () => 'nope' },
|
|
113
|
+
});
|
|
114
|
+
expect(notArray.timers.has('outbox')).toBe(true);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('a request rejected as a whole with an application error rolls back the head and continues', async () => {
|
|
118
|
+
let calls = 0;
|
|
119
|
+
const out = await runPure(drain(env), {
|
|
120
|
+
state: stateWith([1, 2]),
|
|
121
|
+
handlers: {
|
|
122
|
+
'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))] : []),
|
|
123
|
+
'remote.query': () => {
|
|
124
|
+
calls++;
|
|
125
|
+
if (calls === 1) throw 'Parse error at line 1';
|
|
126
|
+
return [ok()];
|
|
127
|
+
},
|
|
128
|
+
'local.execute': () => undefined,
|
|
129
|
+
'ssp.ingest': () => undefined,
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
expect(calls).toBe(2);
|
|
133
|
+
expect(out.state.failedCount).toBe(1);
|
|
134
|
+
expect(out.state.outbox.map((i) => [i.id, i.status])).toEqual([['_00_pending_mutations:m2', 'acked']]);
|
|
135
|
+
const asError = await runPure(drain(env), {
|
|
136
|
+
state: stateWith([1]),
|
|
137
|
+
handlers: {
|
|
138
|
+
'local.query': () => [[pendingRow(1)]],
|
|
139
|
+
'remote.query': () => {
|
|
140
|
+
throw new Error('Parse error at line 1');
|
|
141
|
+
},
|
|
142
|
+
'local.execute': (e: any) => {
|
|
143
|
+
if (e.vars.failed) expect(e.vars.failed.error.message).toBe('Parse error at line 1');
|
|
144
|
+
},
|
|
145
|
+
'ssp.ingest': () => undefined,
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
expect(asError.state.failedCount).toBe(1);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('skips pending rows the store no longer has, does nothing as a follower or when empty, tolerates a failed row delete', async () => {
|
|
152
|
+
const gone = await runPure(drain(env), { state: stateWith([1]), handlers: { 'local.query': () => [[]] } });
|
|
153
|
+
expect(gone.state.outbox).toEqual([]);
|
|
154
|
+
expect(gone.log.filter((e) => e.kind === 'remote.query')).toHaveLength(0);
|
|
155
|
+
const follower = await runPure(drain(env), { state: { ...stateWith([1]), tabRole: 'follower' } });
|
|
156
|
+
expect(follower.log.filter((e) => e.kind === 'local.query')).toHaveLength(0);
|
|
157
|
+
const empty = await runPure(drain(env), { state: buildState() });
|
|
158
|
+
expect(empty.log.filter((e) => e.kind === 'local.query')).toHaveLength(0);
|
|
159
|
+
const delFail = await runPure(drain(env), {
|
|
160
|
+
state: stateWith([1]),
|
|
161
|
+
handlers: {
|
|
162
|
+
'local.query': (e: any) => {
|
|
163
|
+
if (e.sql === 'DELETE $mid') throw new Error('locked');
|
|
164
|
+
return [[pendingRow(1)]];
|
|
165
|
+
},
|
|
166
|
+
'remote.query': () => [ok()],
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
expect(delFail.state.outbox[0].status).toBe('acked');
|
|
170
|
+
expect(delFail.emitted).toContainEqual(expect.objectContaining({ level: 'error' }));
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
describe('rollback', () => {
|
|
175
|
+
it('create: tray move first, local delete, circuit DELETE, version dropped, owner relay when leading', async () => {
|
|
176
|
+
const order: string[] = [];
|
|
177
|
+
const state = { ...stateWith([1]), tabRole: 'leader' as const, tabId: 'tab-a' };
|
|
178
|
+
const row = pendingRow(1, 'create', { id: '_00_pending_mutations:1700000000000_0001_tabz' });
|
|
179
|
+
const out = await runPure(rollback(env, row, { message: 'denied', kind: 'application' }), {
|
|
180
|
+
state: R.setVersions([['thing:1', 1]])(state),
|
|
181
|
+
handlers: {
|
|
182
|
+
'local.execute': (e: any) => void order.push(e.query.sql.includes('_00_failed') || e.query.sql.includes('CREATE ONLY $fid') ? 'tray' : 'revert'),
|
|
183
|
+
'ssp.ingest': (e: any) => void order.push(`circuit:${e.records[0].op}`),
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
expect(order).toEqual(['tray', 'revert', 'circuit:DELETE']);
|
|
187
|
+
expect(out.state.versions.has('thing:1')).toBe(false);
|
|
188
|
+
expect(out.state.failedCount).toBe(1);
|
|
189
|
+
expect(out.state.dirty.has('q')).toBe(true);
|
|
190
|
+
expect(out.emitted).toContainEqual({ type: 'tabs:sendTo', tabId: 'tabz', message: expect.objectContaining({ type: 'mutation-rolled-back' }) });
|
|
191
|
+
expect(out.emitted).toContainEqual({ type: 'tabs:broadcast', message: { type: 'ingest', records: [expect.objectContaining({ op: 'DELETE' })] } });
|
|
192
|
+
expect(out.emitted).toContainEqual({ type: 'tray:changed', count: 1 });
|
|
193
|
+
expect(out.emitted).toContainEqual({ type: 'tabs:broadcast', message: { type: 'failed-mutations-changed', count: 1 } });
|
|
194
|
+
});
|
|
195
|
+
it('update / delete restore beforeRecord and its version; legacy rows read the server row (or end partial)', async () => {
|
|
196
|
+
const upd = await runPure(rollback(env, pendingRow(1, 'update'), { message: 'x', kind: 'application' }), {
|
|
197
|
+
state: stateWith([1]),
|
|
198
|
+
handlers: { 'local.execute': () => undefined, 'ssp.ingest': (e: any) => expect(e.records[0].op).toBe('UPDATE') },
|
|
199
|
+
});
|
|
200
|
+
expect(upd.state.versions.get('thing:1')).toBe(7);
|
|
201
|
+
const del = await runPure(rollback(env, pendingRow(1, 'delete'), { message: 'x', kind: 'application' }), {
|
|
202
|
+
state: stateWith([1]),
|
|
203
|
+
handlers: { 'local.execute': () => undefined, 'ssp.ingest': (e: any) => expect(e.records[0].op).toBe('CREATE') },
|
|
204
|
+
});
|
|
205
|
+
expect(del.state.versions.get('thing:1')).toBe(7);
|
|
206
|
+
const legacy = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
|
|
207
|
+
state: stateWith([1]),
|
|
208
|
+
handlers: {
|
|
209
|
+
'remote.query': () => [ok({ id: new RecordId('thing', '1'), a: 9, _00_rv: 2 })],
|
|
210
|
+
'local.execute': (e: any) => {
|
|
211
|
+
if (e.query.sql.includes('CREATE ONLY $fid')) expect(e.vars.failed.revert).toBe('full');
|
|
212
|
+
},
|
|
213
|
+
'ssp.ingest': () => undefined,
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
expect(legacy.state.versions.get('thing:1')).toBe(2);
|
|
217
|
+
const partial = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
|
|
218
|
+
state: stateWith([1]),
|
|
219
|
+
handlers: {
|
|
220
|
+
'remote.query': () => {
|
|
221
|
+
throw new Error('offline');
|
|
222
|
+
},
|
|
223
|
+
'local.execute': (e: any) => expect(e.vars.failed.revert).toBe('partial'),
|
|
224
|
+
'ssp.ingest': () => undefined,
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
expect(partial.log.filter((e) => e.kind === 'local.execute')).toHaveLength(1);
|
|
228
|
+
const errRow = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
|
|
229
|
+
state: stateWith([1]),
|
|
230
|
+
handlers: { 'remote.query': () => [err('nope')], 'local.execute': () => undefined, 'ssp.ingest': () => undefined },
|
|
231
|
+
});
|
|
232
|
+
expect(errRow.state.failedCount).toBe(1);
|
|
233
|
+
});
|
|
234
|
+
it('every local step is best-effort: tray move, revert and circuit failures are logged', async () => {
|
|
235
|
+
const out = await runPure(rollback(env, pendingRow(1, 'update'), { message: 'x', kind: 'unreplayable' }), {
|
|
236
|
+
state: stateWith([1]),
|
|
237
|
+
handlers: {
|
|
238
|
+
'local.execute': () => {
|
|
239
|
+
throw new Error('disk');
|
|
240
|
+
},
|
|
241
|
+
'ssp.ingest': () => {
|
|
242
|
+
throw new Error('wasm');
|
|
243
|
+
},
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
expect(out.emitted.filter((e) => e.type === 'log')).toHaveLength(3);
|
|
247
|
+
expect(out.state.outbox).toEqual([]);
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe('loadOutbox / refreshFailedCount', () => {
|
|
252
|
+
it('mirrors pending rows, sends unreplayable ones to the tray, refreshes the count, starts a drain', async () => {
|
|
253
|
+
const out = await runPure(loadOutbox(env), {
|
|
254
|
+
state: buildState(),
|
|
255
|
+
handlers: {
|
|
256
|
+
'local.query': (e: any) => {
|
|
257
|
+
if (e.sql.startsWith('SELECT * FROM _00_pending_mutations'))
|
|
258
|
+
return [[pendingRow(1), { id: '_00_pending_mutations:bad', mutationType: 'create', recordId: 'thing:9' }, { tableName: 'thing' }, { mutationType: 'delete' }, 'junk']];
|
|
259
|
+
if (e.sql.startsWith('SELECT count()')) return [[{ count: 4 }]];
|
|
260
|
+
return [];
|
|
261
|
+
},
|
|
262
|
+
'local.execute': () => undefined,
|
|
263
|
+
'ssp.ingest': () => undefined,
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
expect(out.state.outbox.map((i) => i.id)).toEqual(['_00_pending_mutations:m1']);
|
|
267
|
+
expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '_00_pending_mutations:bad' }));
|
|
268
|
+
expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '' }));
|
|
269
|
+
expect(out.state.failedCount).toBe(4);
|
|
270
|
+
expect(out.dispatched).toEqual([{ type: 'Drain' }, { type: 'AdoptPendingWrites' }]);
|
|
271
|
+
const empty = await runPure(loadOutbox(env), { state: buildState(), handlers: { 'local.query': () => [] } });
|
|
272
|
+
expect(empty.dispatched).toEqual([{ type: 'AdoptPendingWrites' }]);
|
|
273
|
+
const missingTable = await runPure(refreshFailedCount(), {
|
|
274
|
+
state: R.setFailedCount(2)(buildState()),
|
|
275
|
+
handlers: {
|
|
276
|
+
'local.query': () => {
|
|
277
|
+
throw new Error('no table');
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
expect(missingTable.state.failedCount).toBe(2);
|
|
282
|
+
const noRows = await runPure(refreshFailedCount(), { state: R.setFailedCount(2)(buildState()), handlers: { 'local.query': () => [[]] } });
|
|
283
|
+
expect(noRows.state.failedCount).toBe(0);
|
|
284
|
+
});
|
|
285
|
+
});
|