@spooky-sync/core 0.0.1-canary.240 → 0.0.1-canary.241
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 +34 -15
- package/README.md +56 -16
- package/dist/index.d.ts +1136 -1846
- package/dist/index.js +10168 -11267
- package/dist/types.d.ts +22 -79
- package/package.json +8 -4
- package/skills/sp00ky-core/SKILL.md +18 -0
- package/src/boot/auth-flip.saga.test.ts +82 -0
- package/src/boot/auth-flip.saga.ts +62 -0
- package/src/boot/boot.saga.test.ts +151 -0
- package/src/boot/boot.saga.ts +128 -0
- package/src/boot/bucket-switch.saga.test.ts +158 -0
- package/src/boot/bucket-switch.saga.ts +115 -0
- package/src/boot/preload.saga.test.ts +51 -0
- package/src/boot/preload.saga.ts +31 -0
- package/src/client/bucket-handle.test.ts +117 -0
- package/src/client/bucket-handle.ts +227 -0
- package/src/client/router.test.ts +56 -0
- package/src/client/router.ts +94 -0
- package/src/client/runtime.test.ts +192 -0
- package/src/client/runtime.ts +296 -0
- package/src/client/services.ts +349 -0
- package/src/client/sp00ky-client.test.ts +241 -0
- package/src/client/sp00ky-client.ts +482 -0
- package/src/index.ts +1 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +54 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +159 -0
- package/src/kernel/events.ts +55 -0
- package/src/kernel/interpreter.test.ts +116 -0
- package/src/kernel/interpreter.ts +143 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/modules/app-release/index.ts +13 -5
- package/src/modules/devtools/index.ts +10 -3
- package/src/modules/devtools/state-shape.test.ts +4 -1
- package/src/modules/feature-flag/index.ts +13 -5
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/{modules/data → mutation}/mutation-id.test.ts +12 -0
- package/src/mutation/push.saga.test.ts +285 -0
- package/src/mutation/push.saga.ts +215 -0
- package/src/mutation/rows.test.ts +201 -0
- package/src/mutation/rows.ts +377 -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 +163 -0
- package/src/mutation/write.saga.ts +166 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +56 -0
- package/src/query/fetch.saga.test.ts +156 -0
- package/src/query/fetch.saga.ts +109 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/{modules/data → query}/id-set-plan.test.ts +12 -2
- package/src/query/lifecycle.saga.test.ts +122 -0
- package/src/query/lifecycle.saga.ts +101 -0
- package/src/query/materialize.saga.test.ts +82 -0
- package/src/query/materialize.saga.ts +75 -0
- package/src/query/materialize.test.ts +50 -0
- package/src/query/materialize.ts +44 -0
- package/src/query/membership.saga.test.ts +246 -0
- package/src/query/membership.saga.ts +208 -0
- package/src/query/membership.test.ts +118 -0
- package/src/query/membership.ts +158 -0
- package/src/query/register.saga.test.ts +251 -0
- package/src/query/register.saga.ts +190 -0
- package/src/query/render-set.test.ts +36 -0
- package/src/query/render-set.ts +60 -0
- package/src/query/sql.test.ts +62 -0
- package/src/query/sql.ts +79 -0
- package/src/{modules/data → query}/window-query.test.ts +18 -0
- package/src/{modules/data → query}/window-query.ts +2 -1
- package/src/services/database/connection-supervisor.test.ts +29 -0
- package/src/services/database/connection-supervisor.ts +7 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +25 -10
- package/src/services/database/local-migrator.ts +2 -2
- package/src/services/database/plan-render.test.ts +1 -1
- package/src/services/database/sqlite-cache-engine.test.ts +4 -3
- package/src/services/database/sqlite-cache-engine.ts +2 -11
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +1 -1
- package/src/services/tabs/protocol.ts +7 -3
- package/src/sp00ky.ts +5 -1854
- package/src/state/client-state.ts +184 -0
- package/src/state/lifecycle.test.ts +118 -0
- package/src/state/lifecycle.ts +86 -0
- package/src/state/reducers.test.ts +280 -0
- package/src/state/reducers.ts +476 -0
- package/src/state/selectors.test.ts +149 -0
- package/src/state/selectors.ts +184 -0
- package/src/sync/connection.saga.test.ts +86 -0
- package/src/sync/connection.saga.ts +85 -0
- package/src/sync/live.saga.test.ts +69 -0
- package/src/sync/live.saga.ts +49 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +31 -3
- package/src/{modules/sync/utils.ts → sync/policy.ts} +67 -5
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +74 -0
- package/src/sync/tabs.saga.ts +92 -0
- package/src/testing/adapters.ts +133 -0
- package/src/testing/build.ts +61 -0
- package/src/testing/fake-services.ts +34 -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 +8 -7
- package/src/utils/utils.test.ts +2 -1
- package/vitest.config.ts +48 -0
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +0 -476
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -210
- package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +0 -271
- package/coverage/lcov-report/src/boot/boot.saga.ts.html +0 -469
- package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +0 -430
- package/coverage/lcov-report/src/boot/index.html +0 -161
- package/coverage/lcov-report/src/boot/preload.saga.ts.html +0 -178
- package/coverage/lcov-report/src/client/bucket-handle.ts.html +0 -766
- package/coverage/lcov-report/src/client/index.html +0 -161
- package/coverage/lcov-report/src/client/router.ts.html +0 -367
- package/coverage/lcov-report/src/client/runtime.ts.html +0 -940
- package/coverage/lcov-report/src/client/sp00ky-client.ts.html +0 -1531
- package/coverage/lcov-report/src/events/index.html +0 -116
- package/coverage/lcov-report/src/events/index.ts.html +0 -877
- package/coverage/lcov-report/src/index.html +0 -146
- package/coverage/lcov-report/src/index.ts.html +0 -202
- package/coverage/lcov-report/src/kernel/constants.ts.html +0 -247
- package/coverage/lcov-report/src/kernel/effects.ts.html +0 -562
- package/coverage/lcov-report/src/kernel/events.ts.html +0 -250
- package/coverage/lcov-report/src/kernel/index.html +0 -176
- package/coverage/lcov-report/src/kernel/interpreter.ts.html +0 -514
- package/coverage/lcov-report/src/kernel/saga.ts.html +0 -304
- package/coverage/lcov-report/src/modules/app-release/index.html +0 -116
- package/coverage/lcov-report/src/modules/app-release/index.ts.html +0 -712
- package/coverage/lcov-report/src/modules/auth/events/index.html +0 -116
- package/coverage/lcov-report/src/modules/auth/events/index.ts.html +0 -142
- package/coverage/lcov-report/src/modules/auth/index.html +0 -116
- package/coverage/lcov-report/src/modules/auth/index.ts.html +0 -1225
- package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +0 -967
- package/coverage/lcov-report/src/modules/crdt/index.html +0 -146
- package/coverage/lcov-report/src/modules/crdt/index.ts.html +0 -1474
- package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +0 -160
- package/coverage/lcov-report/src/modules/devtools/flags.ts.html +0 -1132
- package/coverage/lcov-report/src/modules/devtools/index.html +0 -161
- package/coverage/lcov-report/src/modules/devtools/index.ts.html +0 -2413
- package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +0 -589
- package/coverage/lcov-report/src/modules/devtools/versions.ts.html +0 -415
- package/coverage/lcov-report/src/modules/feature-flag/index.html +0 -116
- package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +0 -1033
- package/coverage/lcov-report/src/modules/index.html +0 -116
- package/coverage/lcov-report/src/modules/ref-tables.ts.html +0 -349
- package/coverage/lcov-report/src/mutation/index.html +0 -191
- package/coverage/lcov-report/src/mutation/jobs.ts.html +0 -208
- package/coverage/lcov-report/src/mutation/mutation-id.ts.html +0 -190
- package/coverage/lcov-report/src/mutation/push.saga.ts.html +0 -730
- package/coverage/lcov-report/src/mutation/rows.ts.html +0 -1216
- package/coverage/lcov-report/src/mutation/tray.saga.ts.html +0 -229
- package/coverage/lcov-report/src/mutation/write.saga.ts.html +0 -583
- package/coverage/lcov-report/src/otel/index.html +0 -116
- package/coverage/lcov-report/src/otel/index.ts.html +0 -466
- package/coverage/lcov-report/src/query/env.ts.html +0 -253
- package/coverage/lcov-report/src/query/fetch.saga.ts.html +0 -412
- package/coverage/lcov-report/src/query/hash.ts.html +0 -139
- package/coverage/lcov-report/src/query/index.html +0 -281
- package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +0 -388
- package/coverage/lcov-report/src/query/materialize.saga.ts.html +0 -310
- package/coverage/lcov-report/src/query/materialize.ts.html +0 -217
- package/coverage/lcov-report/src/query/membership.saga.ts.html +0 -709
- package/coverage/lcov-report/src/query/membership.ts.html +0 -559
- package/coverage/lcov-report/src/query/register.saga.ts.html +0 -655
- package/coverage/lcov-report/src/query/render-set.ts.html +0 -265
- package/coverage/lcov-report/src/query/sql.ts.html +0 -322
- package/coverage/lcov-report/src/query/window-query.ts.html +0 -670
- package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +0 -1894
- package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +0 -766
- package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +0 -1162
- package/coverage/lcov-report/src/services/blobs/index.html +0 -161
- package/coverage/lcov-report/src/services/blobs/index.ts.html +0 -295
- package/coverage/lcov-report/src/services/database/cache-engine.ts.html +0 -664
- package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +0 -1330
- package/coverage/lcov-report/src/services/database/database.ts.html +0 -658
- package/coverage/lcov-report/src/services/database/engine-factory.ts.html +0 -184
- package/coverage/lcov-report/src/services/database/errors.ts.html +0 -187
- package/coverage/lcov-report/src/services/database/events/index.html +0 -116
- package/coverage/lcov-report/src/services/database/events/index.ts.html +0 -184
- package/coverage/lcov-report/src/services/database/index.html +0 -386
- package/coverage/lcov-report/src/services/database/index.ts.html +0 -121
- package/coverage/lcov-report/src/services/database/local-migrator.ts.html +0 -703
- package/coverage/lcov-report/src/services/database/local.ts.html +0 -1633
- package/coverage/lcov-report/src/services/database/plan-render.ts.html +0 -409
- package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +0 -682
- package/coverage/lcov-report/src/services/database/remote.ts.html +0 -1036
- package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +0 -4132
- package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +0 -220
- package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +0 -577
- package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +0 -499
- package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +0 -478
- package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +0 -757
- package/coverage/lcov-report/src/services/database/surql-translate.ts.html +0 -1333
- package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +0 -568
- package/coverage/lcov-report/src/services/logger/index.html +0 -116
- package/coverage/lcov-report/src/services/logger/index.ts.html +0 -154
- package/coverage/lcov-report/src/services/persistence/index.html +0 -146
- package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +0 -163
- package/coverage/lcov-report/src/services/persistence/resilient.ts.html +0 -208
- package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +0 -271
- package/coverage/lcov-report/src/services/stream-processor/index.html +0 -146
- package/coverage/lcov-report/src/services/stream-processor/index.ts.html +0 -3313
- package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +0 -244
- package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +0 -346
- package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +0 -934
- package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +0 -1984
- package/coverage/lcov-report/src/services/tabs/index.html +0 -191
- package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +0 -310
- package/coverage/lcov-report/src/services/tabs/protocol.ts.html +0 -871
- package/coverage/lcov-report/src/services/tabs/support.ts.html +0 -193
- package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +0 -2005
- package/coverage/lcov-report/src/sp00ky.ts.html +0 -100
- package/coverage/lcov-report/src/state/client-state.ts.html +0 -637
- package/coverage/lcov-report/src/state/index.html +0 -161
- package/coverage/lcov-report/src/state/lifecycle.ts.html +0 -343
- package/coverage/lcov-report/src/state/reducers.ts.html +0 -1471
- package/coverage/lcov-report/src/state/selectors.ts.html +0 -637
- package/coverage/lcov-report/src/sync/connection.saga.ts.html +0 -343
- package/coverage/lcov-report/src/sync/index.html +0 -176
- package/coverage/lcov-report/src/sync/live.saga.ts.html +0 -232
- package/coverage/lcov-report/src/sync/policy.ts.html +0 -1606
- package/coverage/lcov-report/src/sync/poll.saga.ts.html +0 -193
- package/coverage/lcov-report/src/sync/tabs.saga.ts.html +0 -361
- package/coverage/lcov-report/src/types.ts.html +0 -2419
- package/coverage/lcov-report/src/utils/blurhash.ts.html +0 -355
- package/coverage/lcov-report/src/utils/error-classification.ts.html +0 -244
- package/coverage/lcov-report/src/utils/index.html +0 -191
- package/coverage/lcov-report/src/utils/index.ts.html +0 -820
- package/coverage/lcov-report/src/utils/parser.ts.html +0 -313
- package/coverage/lcov-report/src/utils/semver.ts.html +0 -175
- package/coverage/lcov-report/src/utils/surql.ts.html +0 -667
- package/coverage/lcov.info +0 -19079
- package/src/modules/cache/cache.relay.test.ts +0 -95
- package/src/modules/cache/index.ts +0 -361
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/data/data.activity.test.ts +0 -109
- package/src/modules/data/data.authority.test.ts +0 -122
- package/src/modules/data/data.heartbeat-wake.test.ts +0 -115
- package/src/modules/data/data.hydration.test.ts +0 -142
- package/src/modules/data/data.membership.test.ts +0 -623
- package/src/modules/data/data.notify-table.test.ts +0 -41
- package/src/modules/data/data.pending-ids.test.ts +0 -199
- package/src/modules/data/data.rebind.test.ts +0 -170
- package/src/modules/data/data.rematerialize.test.ts +0 -114
- package/src/modules/data/data.run.test.ts +0 -113
- package/src/modules/data/data.settled-writes.test.ts +0 -235
- package/src/modules/data/data.status.test.ts +0 -249
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -2745
- package/src/modules/sync/engine.ts +0 -250
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.test.ts +0 -228
- package/src/modules/sync/queue/queue-down.ts +0 -184
- package/src/modules/sync/queue/queue-up.forwarded.test.ts +0 -164
- package/src/modules/sync/queue/queue-up.ts +0 -407
- package/src/modules/sync/scheduler.pause.test.ts +0 -109
- package/src/modules/sync/scheduler.retry.test.ts +0 -237
- package/src/modules/sync/scheduler.ts +0 -286
- package/src/modules/sync/sync.cleanup.test.ts +0 -116
- package/src/modules/sync/sync.health.test.ts +0 -167
- package/src/modules/sync/sync.heartbeat.test.ts +0 -80
- package/src/modules/sync/sync.list-ref-meta.test.ts +0 -193
- package/src/modules/sync/sync.live-removal.test.ts +0 -289
- package/src/modules/sync/sync.reconnect.test.ts +0 -145
- package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +0 -93
- package/src/modules/sync/sync.settled-poll.test.ts +0 -58
- package/src/modules/sync/sync.subquery.test.ts +0 -82
- package/src/modules/sync/sync.tabs.test.ts +0 -249
- package/src/modules/sync/sync.ts +0 -2626
- package/src/sp00ky.auth-order.test.ts +0 -112
- package/src/sp00ky.init-query.test.ts +0 -183
- package/src/sp00ky.local-first.test.ts +0 -60
- /package/src/{modules/data → mutation}/mutation-id.ts +0 -0
|
@@ -0,0 +1,51 @@
|
|
|
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 { pollTick } from './poll.saga';
|
|
8
|
+
|
|
9
|
+
const env = defaultEnv({ tables: [] } as any);
|
|
10
|
+
const ok = (result: unknown) => ({ status: 'OK', result });
|
|
11
|
+
|
|
12
|
+
describe('pollTick', () => {
|
|
13
|
+
it('with no queries: probes connectivity, backs off while idle', async () => {
|
|
14
|
+
const out = await runPure(pollTick(env), { state: R.patchSync({ pollIdleStreak: 2 })(buildState()), handlers: { 'remote.query': () => [ok(true)] } });
|
|
15
|
+
expect(out.dispatched).toEqual([{ type: 'SyncOutcome', ok: true }]);
|
|
16
|
+
expect(out.state.sync.pollIdleStreak).toBe(3);
|
|
17
|
+
expect(out.timers.get('poll')).toEqual({ ms: 4000, event: { type: 'PollTick' } });
|
|
18
|
+
const failed = await runPure(pollTick(env), {
|
|
19
|
+
state: buildState(),
|
|
20
|
+
handlers: {
|
|
21
|
+
'remote.query': () => {
|
|
22
|
+
throw new Error('offline');
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
expect(failed.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('offline') }]);
|
|
27
|
+
});
|
|
28
|
+
it('with queries: reads membership; a change or an acked write resets the streak', async () => {
|
|
29
|
+
const entry = buildEntry({ def: { hash: 'a', id: new RecordId('_00_query', 'a') }, lifecycle: { phase: 'live' }, serverState: 'ready' });
|
|
30
|
+
const changed = await runPure(pollTick(env), {
|
|
31
|
+
state: R.patchSync({ pollIdleStreak: 5 })(buildState([entry])),
|
|
32
|
+
handlers: {
|
|
33
|
+
'remote.query': () => [ok([{ out: new RecordId('thing', '1'), version: 1 }]), ok({ rowCount: 1, state: 'ready' }), ok([])],
|
|
34
|
+
'local.upsert': () => undefined,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
expect(changed.state.sync.pollIdleStreak).toBe(0);
|
|
38
|
+
expect(changed.timers.get('poll')!.ms).toBe(500);
|
|
39
|
+
const quiet = await runPure(pollTick(env), {
|
|
40
|
+
state: R.patchSync({ pollIdleStreak: 1 })(buildState([entry])),
|
|
41
|
+
handlers: { 'remote.query': () => [ok([]), ok({ rowCount: 0, state: 'ready' }), ok([])], 'local.upsert': () => undefined },
|
|
42
|
+
});
|
|
43
|
+
expect(quiet.state.sync.pollIdleStreak).toBe(2);
|
|
44
|
+
expect(quiet.timers.get('poll')!.ms).toBe(2000);
|
|
45
|
+
const acked = await runPure(pollTick(env), {
|
|
46
|
+
state: buildState([entry], R.patchSync({ pollIdleStreak: 4 }), R.outboxReplace([buildOutboxItem({ status: 'acked', ackedAt: 1 })])),
|
|
47
|
+
handlers: { 'remote.query': () => [ok([]), ok({ rowCount: 0, state: 'ready' }), ok([])], 'local.upsert': () => undefined },
|
|
48
|
+
});
|
|
49
|
+
expect(acked.state.sync.pollIdleStreak).toBe(0);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Saga } from '../kernel/saga';
|
|
2
|
+
import { fx } from '../kernel/effects';
|
|
3
|
+
import * as R from '../state/reducers';
|
|
4
|
+
import { activeHashes, hasAckedWrites } from '../state/selectors';
|
|
5
|
+
import type { SagaEnv } from '../query/env';
|
|
6
|
+
import { readMembership } from '../query/membership.saga';
|
|
7
|
+
import { listRefPollDelayMs } from './policy';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The `_00_list_ref` poll: the safety net under LIVE. Reads every active
|
|
11
|
+
* query's membership on a backoff that snaps to the base cadence whenever
|
|
12
|
+
* something changed (or an acked write still waits for membership) and
|
|
13
|
+
* coasts up to the cap while quiet. With no queries it probes connectivity.
|
|
14
|
+
*/
|
|
15
|
+
export function* pollTick(env: SagaEnv): Saga<void> {
|
|
16
|
+
const [hashes, streak, acked] = (yield fx.state.read((s) => [activeHashes(s), s.sync.pollIdleStreak, hasAckedWrites(s)])) as [
|
|
17
|
+
string[],
|
|
18
|
+
number,
|
|
19
|
+
boolean,
|
|
20
|
+
];
|
|
21
|
+
let changed = false;
|
|
22
|
+
if (hashes.length === 0) {
|
|
23
|
+
try {
|
|
24
|
+
yield fx.remote.query('RETURN true', undefined, env.remoteTimeoutMs);
|
|
25
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: true });
|
|
26
|
+
} catch (error) {
|
|
27
|
+
yield fx.dispatch({ type: 'SyncOutcome', ok: false, error });
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
const result = yield* readMembership(env, hashes);
|
|
31
|
+
changed = result.changed;
|
|
32
|
+
}
|
|
33
|
+
const idleStreak = changed || acked ? 0 : streak + 1;
|
|
34
|
+
yield fx.state.update(R.patchSync({ pollIdleStreak: idleStreak }));
|
|
35
|
+
yield fx.timer.set('poll', listRefPollDelayMs({ idleStreak, baseIntervalMs: env.pollBaseMs }), { type: 'PollTick' });
|
|
36
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { runPure } from '../testing/run-pure';
|
|
3
|
+
import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
|
|
4
|
+
import * as R from '../state/reducers';
|
|
5
|
+
import { defaultEnv } from '../query/env';
|
|
6
|
+
import { setRole, tabMessage } from './tabs.saga';
|
|
7
|
+
|
|
8
|
+
const env = defaultEnv({ tables: [] } as any);
|
|
9
|
+
|
|
10
|
+
describe('setRole', () => {
|
|
11
|
+
it('leader: loads the outbox and starts live/poll/registrations; follower: stops its timers; same role is a no-op', async () => {
|
|
12
|
+
const leader = await runPure(setRole(env, 'leader'), { state: buildState(), handlers: { 'local.query': () => [] } });
|
|
13
|
+
expect(leader.state.tabRole).toBe('leader');
|
|
14
|
+
expect(leader.dispatched).toEqual([{ type: 'LiveStart' }, { type: 'PollTick' }, { type: 'EnsureRegistered' }]);
|
|
15
|
+
const follower = await runPure(setRole(env, 'follower'), { state: R.patchSync({ liveUuid: 'u' })(buildState()) });
|
|
16
|
+
expect(follower.state.tabRole).toBe('follower');
|
|
17
|
+
expect(follower.state.sync.liveUuid).toBeNull();
|
|
18
|
+
expect(follower.log.filter((e) => e.kind === 'timer.clear').map((e) => (e as any).key)).toEqual(['poll', 'outbox']);
|
|
19
|
+
const same = await runPure(setRole(env, 'solo'), { state: buildState() });
|
|
20
|
+
expect(same.log).toHaveLength(1);
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe('tabMessage', () => {
|
|
25
|
+
const s = () => buildState([buildEntry({ def: { hash: 'a', tableName: 'thing' } })], R.outboxReplace([buildOutboxItem({ id: 'm1', recordId: 'thing:1' })]));
|
|
26
|
+
it('ignores junk', async () => {
|
|
27
|
+
for (const junk of [null, 'x', {}, { type: 'weird' }, { type: 'ingest', records: [] }, { type: 'membership-dirty' }, { type: 'failed-mutations-changed' }]) {
|
|
28
|
+
const out = await runPure(tabMessage(env, junk), { state: s() });
|
|
29
|
+
expect(out.emitted).toEqual([]);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
it('ingest: feeds the circuit, tracks versions, dirties tables; a failing ingest is logged', async () => {
|
|
33
|
+
const msg = {
|
|
34
|
+
type: 'ingest',
|
|
35
|
+
records: [
|
|
36
|
+
{ table: 'thing', op: 'CREATE', id: 'thing:2', record: { _00_rv: 3 } },
|
|
37
|
+
{ table: 'thing', op: 'DELETE', id: 'thing:1', record: {} },
|
|
38
|
+
{ table: 'other', op: 'UPDATE', id: 'other:1', record: {} },
|
|
39
|
+
],
|
|
40
|
+
};
|
|
41
|
+
const out = await runPure(tabMessage(env, msg), { state: R.setVersions([['thing:1', 1]])(s()), handlers: { 'ssp.ingest': () => undefined } });
|
|
42
|
+
expect(out.state.versions.get('thing:2')).toBe(3);
|
|
43
|
+
expect(out.state.versions.get('other:1')).toBe(0);
|
|
44
|
+
expect(out.state.versions.has('thing:1')).toBe(false);
|
|
45
|
+
expect(out.state.dirty.has('a')).toBe(true);
|
|
46
|
+
const failing = await runPure(tabMessage(env, msg), {
|
|
47
|
+
state: s(),
|
|
48
|
+
handlers: {
|
|
49
|
+
'ssp.ingest': () => {
|
|
50
|
+
throw new Error('wasm');
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
expect(failing.emitted).toEqual([expect.objectContaining({ level: 'warn' })]);
|
|
55
|
+
});
|
|
56
|
+
it('membership-dirty, outbox-changed (leader only), settled, rolled-back, tray count', async () => {
|
|
57
|
+
const dirty = await runPure(tabMessage(env, { type: 'membership-dirty', hashes: ['a'] }), { state: { ...s(), tabRole: 'follower' } });
|
|
58
|
+
expect(dirty.state.membershipDirty.has('a')).toBe(true);
|
|
59
|
+
const ob = await runPure(tabMessage(env, { type: 'outbox-changed', mutationId: 'm' }), { state: { ...s(), tabRole: 'leader' }, handlers: { 'local.query': () => [] } });
|
|
60
|
+
expect(ob.log.some((e) => e.kind === 'local.query')).toBe(true);
|
|
61
|
+
const obFollower = await runPure(tabMessage(env, { type: 'outbox-changed', mutationId: 'm' }), { state: { ...s(), tabRole: 'follower' } });
|
|
62
|
+
expect(obFollower.log.some((e) => e.kind === 'local.query')).toBe(false);
|
|
63
|
+
const settled = await runPure(tabMessage(env, { type: 'mutation-settled', mutationId: 'm1', recordId: 'thing:1', eventType: 'create' }), { state: s(), now: 9 });
|
|
64
|
+
expect(settled.state.outbox[0]).toMatchObject({ status: 'acked', ackedAt: 9 });
|
|
65
|
+
expect(settled.emitted).toEqual([{ type: 'mutation:settled', mutationId: 'm1', recordId: 'thing:1', eventType: 'create' }]);
|
|
66
|
+
const rolled = await runPure(tabMessage(env, { type: 'mutation-rolled-back', mutationId: 'm1', recordId: 'thing:1', eventType: 'create', error: 'denied' }), { state: s() });
|
|
67
|
+
expect(rolled.state.outbox).toEqual([]);
|
|
68
|
+
expect(rolled.state.dirty.has('a')).toBe(true);
|
|
69
|
+
expect(rolled.emitted[0]).toMatchObject({ type: 'mutation:rolled-back', error: 'denied' });
|
|
70
|
+
const tray = await runPure(tabMessage(env, { type: 'failed-mutations-changed', count: 4 }), { state: s() });
|
|
71
|
+
expect(tray.state.failedCount).toBe(4);
|
|
72
|
+
expect(tray.emitted).toEqual([{ type: 'tray:changed', count: 4 }]);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { Saga } from '../kernel/saga';
|
|
2
|
+
import { fx } from '../kernel/effects';
|
|
3
|
+
import type { IngestRecord } from '../services/stream-processor/index';
|
|
4
|
+
import type { ClientState, TabRole } from '../state/client-state';
|
|
5
|
+
import * as R from '../state/reducers';
|
|
6
|
+
import type { SagaEnv } from '../query/env';
|
|
7
|
+
import { loadOutbox } from '../mutation/push.saga';
|
|
8
|
+
import { liveChange } from './live.saga';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Shared-tabs role changes. The leader owns the outbox drain, the poll and
|
|
12
|
+
* LIVE; a follower keeps its own circuit and materialization but gets
|
|
13
|
+
* membership dirt, acks and rollbacks relayed.
|
|
14
|
+
*/
|
|
15
|
+
export function* setRole(env: SagaEnv, role: TabRole): Saga<void> {
|
|
16
|
+
const prev = (yield fx.state.read((s) => s.tabRole)) as TabRole;
|
|
17
|
+
if (prev === role) return;
|
|
18
|
+
yield fx.state.update(R.setTabRole(role));
|
|
19
|
+
if (role === 'follower') {
|
|
20
|
+
yield fx.timer.clear('poll');
|
|
21
|
+
yield fx.timer.clear('outbox');
|
|
22
|
+
yield fx.state.update(R.patchSync({ liveUuid: null, liveTable: null }));
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
yield* loadOutbox(env);
|
|
26
|
+
yield fx.dispatch({ type: 'LiveStart' });
|
|
27
|
+
yield fx.dispatch({ type: 'PollTick' });
|
|
28
|
+
yield fx.dispatch({ type: 'EnsureRegistered' });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type TabMessage =
|
|
32
|
+
| { type: 'ingest'; records: IngestRecord[] }
|
|
33
|
+
| { type: 'membership-dirty'; hashes: string[] }
|
|
34
|
+
| { type: 'outbox-changed'; mutationId: string }
|
|
35
|
+
| { type: 'mutation-settled'; mutationId: string; recordId: string; eventType: string }
|
|
36
|
+
| { type: 'mutation-rolled-back'; mutationId: string; recordId: string; eventType: string; error: string }
|
|
37
|
+
| { type: 'failed-mutations-changed'; count: number };
|
|
38
|
+
|
|
39
|
+
/** A message from another tab of the same origin. */
|
|
40
|
+
export function* tabMessage(env: SagaEnv, raw: unknown): Saga<void> {
|
|
41
|
+
const msg = raw as TabMessage | null;
|
|
42
|
+
if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;
|
|
43
|
+
const role = (yield fx.state.read((s) => s.tabRole)) as ClientState['tabRole'];
|
|
44
|
+
switch (msg.type) {
|
|
45
|
+
case 'ingest': {
|
|
46
|
+
if (!Array.isArray(msg.records) || msg.records.length === 0) return;
|
|
47
|
+
try {
|
|
48
|
+
yield fx.ssp.ingest(msg.records);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
yield fx.emit({ type: 'log', level: 'warn', message: 'relayed ingest failed', data: { error } });
|
|
51
|
+
}
|
|
52
|
+
yield fx.state.update(
|
|
53
|
+
R.compose(
|
|
54
|
+
R.setVersions(
|
|
55
|
+
msg.records
|
|
56
|
+
.filter((r) => r.op !== 'DELETE')
|
|
57
|
+
.map((r) => [r.id, typeof r.record?._00_rv === 'number' ? (r.record._00_rv as number) : 0] as const)
|
|
58
|
+
),
|
|
59
|
+
R.deleteVersions(msg.records.filter((r) => r.op === 'DELETE').map((r) => r.id)),
|
|
60
|
+
...[...new Set(msg.records.map((r) => r.table))].map((t) => R.markTableDirty(t))
|
|
61
|
+
)
|
|
62
|
+
);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
case 'membership-dirty':
|
|
66
|
+
if (Array.isArray(msg.hashes)) yield* liveChange(msg.hashes);
|
|
67
|
+
return;
|
|
68
|
+
case 'outbox-changed':
|
|
69
|
+
if (role !== 'leader') return;
|
|
70
|
+
yield* loadOutbox(env);
|
|
71
|
+
return;
|
|
72
|
+
case 'mutation-settled': {
|
|
73
|
+
const now = (yield fx.now()) as number;
|
|
74
|
+
yield fx.state.update(R.outboxAck(msg.mutationId, now));
|
|
75
|
+
yield fx.emit({ type: 'mutation:settled', mutationId: msg.mutationId, recordId: msg.recordId, eventType: msg.eventType });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
case 'mutation-rolled-back': {
|
|
79
|
+
const table = msg.recordId.slice(0, msg.recordId.indexOf(':'));
|
|
80
|
+
yield fx.state.update(R.compose(R.outboxRemove(msg.mutationId), R.markTableDirty(table)));
|
|
81
|
+
yield fx.emit({ type: 'mutation:rolled-back', mutationId: msg.mutationId, recordId: msg.recordId, eventType: msg.eventType, error: msg.error });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
case 'failed-mutations-changed':
|
|
85
|
+
if (typeof msg.count !== 'number') return;
|
|
86
|
+
yield fx.state.update(R.setFailedCount(msg.count));
|
|
87
|
+
yield fx.emit({ type: 'tray:changed', count: msg.count });
|
|
88
|
+
return;
|
|
89
|
+
default:
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { Adapters, InterpreterHost } from '../kernel/interpreter';
|
|
2
|
+
import type { ServiceCalls } from '../kernel/effects';
|
|
3
|
+
import type { OutEvent, RuntimeEvent } from '../kernel/events';
|
|
4
|
+
import type { ClientState } from '../state/client-state';
|
|
5
|
+
import { emptyState } from '../state/client-state';
|
|
6
|
+
import { sha256Hex } from './run-pure';
|
|
7
|
+
|
|
8
|
+
export interface FakeTimers {
|
|
9
|
+
pending: Map<string, { ms: number; fire: () => void }>;
|
|
10
|
+
fire(key: string): void;
|
|
11
|
+
fireAll(): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Recording adapters for interpreter / runtime / facade tests. Every call is
|
|
16
|
+
* logged; behaviour is scripted by overriding the methods you care about.
|
|
17
|
+
*/
|
|
18
|
+
export function fakeAdapters(over: {
|
|
19
|
+
local?: Partial<Adapters['local']>;
|
|
20
|
+
remote?: Partial<Adapters['remote']>;
|
|
21
|
+
ssp?: Partial<Adapters['ssp']>;
|
|
22
|
+
services?: Partial<ServiceCalls>;
|
|
23
|
+
now?: number;
|
|
24
|
+
} = {}) {
|
|
25
|
+
const calls: Array<[string, unknown[]]> = [];
|
|
26
|
+
const log = (name: string, ...args: unknown[]) => calls.push([name, args]);
|
|
27
|
+
let now = over.now ?? 1_700_000_000_000;
|
|
28
|
+
let epoch = 0;
|
|
29
|
+
const timers: FakeTimers = {
|
|
30
|
+
pending: new Map(),
|
|
31
|
+
fire(key) {
|
|
32
|
+
const t = timers.pending.get(key);
|
|
33
|
+
if (!t) return;
|
|
34
|
+
timers.pending.delete(key);
|
|
35
|
+
t.fire();
|
|
36
|
+
},
|
|
37
|
+
fireAll() {
|
|
38
|
+
for (const key of [...timers.pending.keys()]) timers.fire(key);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
const services = new Proxy({} as ServiceCalls, {
|
|
42
|
+
get(_t, name: string) {
|
|
43
|
+
return (...args: unknown[]) => {
|
|
44
|
+
log(`service.${name}`, ...args);
|
|
45
|
+
const fn = (over.services as Record<string, (...a: unknown[]) => unknown> | undefined)?.[name];
|
|
46
|
+
return fn ? fn(...args) : undefined;
|
|
47
|
+
};
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
let ids = 0;
|
|
51
|
+
const adapters: Adapters = {
|
|
52
|
+
local: {
|
|
53
|
+
get epoch() {
|
|
54
|
+
return epoch;
|
|
55
|
+
},
|
|
56
|
+
query: (async (sql: string, vars?: Record<string, unknown>) => (log('local.query', sql, vars), [])) as Adapters['local']['query'],
|
|
57
|
+
execute: (async (q: { sql: string }, vars?: Record<string, unknown>) => (log('local.execute', q.sql, vars), undefined)) as Adapters['local']['execute'],
|
|
58
|
+
select: async (plan, params) => (log('local.select', plan, params), []),
|
|
59
|
+
getById: async (table, id) => (log('local.getById', table, id), null),
|
|
60
|
+
upsert: async (table, id, data, mode) => void log('local.upsert', table, id, data, mode),
|
|
61
|
+
delete: async (table, id) => void log('local.delete', table, id),
|
|
62
|
+
...over.local,
|
|
63
|
+
},
|
|
64
|
+
remote: {
|
|
65
|
+
queryResponses: async (sql, vars) => (log('remote.query', sql, vars), []),
|
|
66
|
+
live: async (table) => (log('remote.live', table), 'live-uuid'),
|
|
67
|
+
kill: async (uuid) => void log('remote.kill', uuid),
|
|
68
|
+
...over.remote,
|
|
69
|
+
},
|
|
70
|
+
ssp: {
|
|
71
|
+
registerQueryPlan: (plan) => (log('ssp.register', plan.queryHash), { queryHash: plan.queryHash, localArray: [] }),
|
|
72
|
+
unregisterQueryPlan: (hash) => void log('ssp.unregister', hash),
|
|
73
|
+
ingestMany: (records) => (log('ssp.ingest', records), records),
|
|
74
|
+
...over.ssp,
|
|
75
|
+
},
|
|
76
|
+
timers: {
|
|
77
|
+
set: (key, ms, fire) => void timers.pending.set(key, { ms, fire }),
|
|
78
|
+
clear: (key) => void timers.pending.delete(key),
|
|
79
|
+
},
|
|
80
|
+
clock: { now: () => now },
|
|
81
|
+
ids: { mutation: () => `_00_pending_mutations:${String(++ids).padStart(13, '0')}_0001_tab`, salt: () => `salt-${++ids}` },
|
|
82
|
+
hash: sha256Hex,
|
|
83
|
+
services,
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
adapters,
|
|
87
|
+
calls,
|
|
88
|
+
timers,
|
|
89
|
+
names: () => calls.map(([n]) => n),
|
|
90
|
+
advance(ms: number) {
|
|
91
|
+
now += ms;
|
|
92
|
+
},
|
|
93
|
+
bumpEpoch() {
|
|
94
|
+
epoch += 1;
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A minimal host: holds state, resolves waits when the predicate holds after an update. */
|
|
100
|
+
export function fakeHost(initial: ClientState = emptyState({ tabId: 'tab-a' })) {
|
|
101
|
+
let state = initial;
|
|
102
|
+
const emitted: OutEvent[] = [];
|
|
103
|
+
const dispatched: RuntimeEvent[] = [];
|
|
104
|
+
const waiters = new Set<{ until: (s: ClientState) => boolean; resolve: () => void; reject: (e: unknown) => void }>();
|
|
105
|
+
const check = () => {
|
|
106
|
+
for (const w of [...waiters]) {
|
|
107
|
+
if (w.until(state)) {
|
|
108
|
+
waiters.delete(w);
|
|
109
|
+
w.resolve();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const host: InterpreterHost = {
|
|
114
|
+
getState: () => state,
|
|
115
|
+
setState: (next) => {
|
|
116
|
+
state = next;
|
|
117
|
+
check();
|
|
118
|
+
},
|
|
119
|
+
waitFor: (until, signal) =>
|
|
120
|
+
new Promise<void>((resolve, reject) => {
|
|
121
|
+
if (until(state)) return resolve();
|
|
122
|
+
const w = { until, resolve, reject };
|
|
123
|
+
waiters.add(w);
|
|
124
|
+
signal?.addEventListener('abort', () => {
|
|
125
|
+
waiters.delete(w);
|
|
126
|
+
reject(new Error('aborted'));
|
|
127
|
+
});
|
|
128
|
+
}),
|
|
129
|
+
emit: (e) => void emitted.push(e),
|
|
130
|
+
dispatch: (e) => void dispatched.push(e),
|
|
131
|
+
};
|
|
132
|
+
return { host, emitted, dispatched, get state() { return state; }, waiters };
|
|
133
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { RecordId } from 'surrealdb';
|
|
2
|
+
import type { ClientState, OutboxItem, QueryDefinition, QueryEntry } from '../state/client-state';
|
|
3
|
+
import { emptyState, emptyTelemetry } from '../state/client-state';
|
|
4
|
+
import { seedLifecycle } from '../state/lifecycle';
|
|
5
|
+
import { compose, putQuery } from '../state/reducers';
|
|
6
|
+
import type { Reducer } from '../state/reducers';
|
|
7
|
+
|
|
8
|
+
type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | T[K] : T[K] };
|
|
9
|
+
|
|
10
|
+
export function buildDefinition(over: Partial<QueryDefinition> = {}): QueryDefinition {
|
|
11
|
+
const hash = over.hash ?? 'h1';
|
|
12
|
+
return {
|
|
13
|
+
id: over.id ?? (new RecordId('_00_query', hash) as any),
|
|
14
|
+
hash,
|
|
15
|
+
viewKey: over.viewKey ?? `view-${hash}`,
|
|
16
|
+
surql: over.surql ?? 'SELECT * FROM thing',
|
|
17
|
+
params: over.params ?? {},
|
|
18
|
+
plan: over.plan,
|
|
19
|
+
ttl: over.ttl ?? '10m',
|
|
20
|
+
ttlMs: over.ttlMs ?? 600_000,
|
|
21
|
+
tableName: over.tableName ?? 'thing',
|
|
22
|
+
createdAt: over.createdAt ?? 1_700_000_000_000,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function buildEntry(over: DeepPartial<QueryEntry> & { def?: Partial<QueryDefinition> } = {}): QueryEntry {
|
|
27
|
+
const def = buildDefinition(over.def ?? {});
|
|
28
|
+
return {
|
|
29
|
+
def,
|
|
30
|
+
lifecycle: { ...seedLifecycle(false), ...(over.lifecycle as object) },
|
|
31
|
+
remoteArray: (over.remoteArray as QueryEntry['remoteArray']) ?? [],
|
|
32
|
+
localArray: (over.localArray as QueryEntry['localArray']) ?? [],
|
|
33
|
+
subqueryRemoteArray: (over.subqueryRemoteArray as QueryEntry['subqueryRemoteArray']) ?? [],
|
|
34
|
+
records: (over.records as QueryEntry['records']) ?? [],
|
|
35
|
+
serverState: over.serverState ?? null,
|
|
36
|
+
subscribers: over.subscribers ?? 0,
|
|
37
|
+
lastSubscriberLeftAt: over.lastSubscriberLeftAt ?? null,
|
|
38
|
+
lastHeartbeatAt: over.lastHeartbeatAt ?? null,
|
|
39
|
+
lastPolledAt: over.lastPolledAt ?? null,
|
|
40
|
+
registerAttempts: over.registerAttempts ?? 0,
|
|
41
|
+
telemetry: { ...emptyTelemetry(), ...(over.telemetry as object) },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function buildOutboxItem(over: Partial<OutboxItem> = {}): OutboxItem {
|
|
46
|
+
return {
|
|
47
|
+
id: over.id ?? 'm1',
|
|
48
|
+
type: over.type ?? 'create',
|
|
49
|
+
recordId: over.recordId ?? 'thing:1',
|
|
50
|
+
table: over.table ?? 'thing',
|
|
51
|
+
status: over.status ?? 'pending',
|
|
52
|
+
ackedAt: over.ackedAt ?? null,
|
|
53
|
+
attempts: over.attempts ?? 0,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A state holding the given entries, with `dirty` cleared (as after materialization). */
|
|
58
|
+
export function buildState(entries: QueryEntry[] = [], ...extra: Reducer[]): ClientState {
|
|
59
|
+
const base = compose(...entries.map(putQuery))(emptyState({ tabId: 'tab-a' }));
|
|
60
|
+
return compose(...extra)({ ...base, dirty: new Set() });
|
|
61
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { Services } from '../client/services';
|
|
3
|
+
|
|
4
|
+
const noop = () => {};
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The legacy services the facade constructs around, as inert stubs. Only the
|
|
8
|
+
* members the facade touches at construction / close time exist; sagas never
|
|
9
|
+
* see these (they go through the adapters' `service` calls).
|
|
10
|
+
*/
|
|
11
|
+
export function fakeServiceBundle<S extends SchemaStructure>(over: Partial<Services<S>> = {}): Services<S> & { authListeners: Array<(u: string | null) => void>; connectionListeners: Array<(s: string) => void>; receivers: unknown[] } {
|
|
12
|
+
const logger: any = { debug: noop, info: noop, warn: noop, error: noop, trace: noop, child: () => logger };
|
|
13
|
+
const authListeners: Array<(u: string | null) => void> = [];
|
|
14
|
+
const connectionListeners: Array<(s: string) => void> = [];
|
|
15
|
+
const receivers: unknown[] = [];
|
|
16
|
+
const events = { subscribe: noop };
|
|
17
|
+
const bundle = {
|
|
18
|
+
logger,
|
|
19
|
+
local: { getEvents: () => events, getClient: () => 'local-client', storageHealth: undefined, subscribeToStorageHealth: undefined, close: async () => undefined } as any,
|
|
20
|
+
remote: { getEvents: () => events, getClient: () => ({ authenticate: async (t: string) => t, invalidate: async () => undefined }), setAuthToken: noop, query: async () => ['remote'], close: async () => undefined } as any,
|
|
21
|
+
connectionSupervisor: { subscribe: (cb: (s: string) => void) => (connectionListeners.push(cb), noop), dispose: noop } as any,
|
|
22
|
+
blobs: { stats: () => ({ entries: 0 }), close: async () => undefined } as any,
|
|
23
|
+
persistence: { set: async () => undefined, get: async () => null, remove: async () => undefined },
|
|
24
|
+
streamProcessor: { addReceiver: (r: unknown) => void receivers.push(r), checkpoint: async () => undefined, dispose: noop } as any,
|
|
25
|
+
migrator: {} as any,
|
|
26
|
+
crdt: { closeAll: noop, dispose: noop, open: async () => 'field', close: noop } as any,
|
|
27
|
+
auth: { subscribe: (cb: (u: string | null) => void) => (authListeners.push(cb), noop), currentUser: null, isAuthenticated: false, eventSystem: { subscribe: noop } } as any,
|
|
28
|
+
tabs: null,
|
|
29
|
+
tabsUnsupportedReason: 'test',
|
|
30
|
+
tabId: 'tab-test',
|
|
31
|
+
...over,
|
|
32
|
+
} as Services<S>;
|
|
33
|
+
return Object.assign(bundle, { authListeners, connectionListeners, receivers });
|
|
34
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { fx } from '../kernel/effects';
|
|
3
|
+
import type { Saga } from '../kernel/saga';
|
|
4
|
+
import { bySqlPrefix, runPure, UnhandledEffectError } from './run-pure';
|
|
5
|
+
import { setFailedCount } from '../state/reducers';
|
|
6
|
+
|
|
7
|
+
describe('runPure', () => {
|
|
8
|
+
it('handles state, clock, ids, hash, timers, emit, dispatch', async () => {
|
|
9
|
+
function* saga(): Saga<Record<string, unknown>> {
|
|
10
|
+
const before = (yield fx.state.read((s) => s.failedCount)) as number;
|
|
11
|
+
yield fx.state.update(setFailedCount(3));
|
|
12
|
+
const after = (yield fx.state.read((s) => s.failedCount)) as number;
|
|
13
|
+
const now = (yield fx.now()) as number;
|
|
14
|
+
const id1 = (yield fx.id('mutation')) as string;
|
|
15
|
+
const id2 = (yield fx.id('salt')) as string;
|
|
16
|
+
const hash = (yield fx.hash('abc')) as string;
|
|
17
|
+
yield fx.timer.set('k', 10, { type: 'Drain' });
|
|
18
|
+
yield fx.timer.set('k', 20, { type: 'Drain' });
|
|
19
|
+
yield fx.timer.set('j', 5, { type: 'FetchRows' });
|
|
20
|
+
yield fx.timer.clear('j');
|
|
21
|
+
yield fx.emit({ type: 'tray:changed', count: 1 });
|
|
22
|
+
yield fx.dispatch({ type: 'FetchRows' });
|
|
23
|
+
return { before, after, now, id1, id2, hash };
|
|
24
|
+
}
|
|
25
|
+
const out = await runPure(saga(), { now: 5 });
|
|
26
|
+
expect(out.result).toEqual({
|
|
27
|
+
before: 0,
|
|
28
|
+
after: 3,
|
|
29
|
+
now: 5,
|
|
30
|
+
id1: 'mutation-1',
|
|
31
|
+
id2: 'salt-2',
|
|
32
|
+
hash: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
|
|
33
|
+
});
|
|
34
|
+
expect(out.state.failedCount).toBe(3);
|
|
35
|
+
expect([...out.timers.entries()]).toEqual([['k', { ms: 20, event: { type: 'Drain' } }]]);
|
|
36
|
+
expect(out.emitted).toEqual([{ type: 'tray:changed', count: 1 }]);
|
|
37
|
+
expect(out.dispatched).toEqual([{ type: 'FetchRows' }]);
|
|
38
|
+
expect(out.log.map((e) => e.kind)[0]).toBe('state.read');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('state.wait passes when the predicate holds and throws when it would block', async () => {
|
|
42
|
+
function* ok(): Saga<string> {
|
|
43
|
+
yield fx.state.wait((s) => s.failedCount === 0);
|
|
44
|
+
return 'passed';
|
|
45
|
+
}
|
|
46
|
+
await expect(runPure(ok())).resolves.toMatchObject({ result: 'passed' });
|
|
47
|
+
function* blocked(): Saga<void> {
|
|
48
|
+
yield fx.state.wait((s) => s.failedCount === 9);
|
|
49
|
+
}
|
|
50
|
+
await expect(runPure(blocked())).rejects.toThrow(/would block/);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('routes adapter effects to handlers and throws on unhandled ones', async () => {
|
|
54
|
+
function* saga(): Saga<unknown> {
|
|
55
|
+
return yield fx.remote.query('RETURN true');
|
|
56
|
+
}
|
|
57
|
+
const out = await runPure(saga(), { handlers: { 'remote.query': () => [{ status: 'OK', result: true }] } });
|
|
58
|
+
expect(out.result).toEqual([{ status: 'OK', result: true }]);
|
|
59
|
+
await expect(runPure(saga())).rejects.toBeInstanceOf(UnhandledEffectError);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('all returns settled results in order and keeps going after a failure', async () => {
|
|
63
|
+
function* saga(): Saga<unknown> {
|
|
64
|
+
return yield fx.all([fx.remote.query('A'), fx.remote.query('B'), fx.now()]);
|
|
65
|
+
}
|
|
66
|
+
const out = await runPure(saga(), {
|
|
67
|
+
now: 1,
|
|
68
|
+
handlers: {
|
|
69
|
+
'remote.query': (e) => {
|
|
70
|
+
if ((e as { sql: string }).sql === 'B') throw new Error('nope');
|
|
71
|
+
return 'a';
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
expect(out.result).toEqual([
|
|
76
|
+
{ ok: true, value: 'a' },
|
|
77
|
+
{ ok: false, error: new Error('nope') },
|
|
78
|
+
{ ok: true, value: 1 },
|
|
79
|
+
]);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('bySqlPrefix answers by prefix and rejects unknown SQL', async () => {
|
|
83
|
+
const handler = bySqlPrefix([
|
|
84
|
+
['SELECT', () => 'rows'],
|
|
85
|
+
['DELETE', () => 'gone'],
|
|
86
|
+
]);
|
|
87
|
+
expect(handler(fx.local.query('SELECT * FROM x'), {} as never)).toBe('rows');
|
|
88
|
+
expect(handler(fx.local.query('DELETE x'), {} as never)).toBe('gone');
|
|
89
|
+
expect(() => handler(fx.local.query('UPDATE x'), {} as never)).toThrow(/no scripted answer/);
|
|
90
|
+
expect(() => handler(fx.now(), {} as never)).toThrow(/no scripted answer/);
|
|
91
|
+
});
|
|
92
|
+
});
|