@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +58 -21
- package/README.md +59 -16
- package/dist/index.d.ts +2235 -908
- package/dist/index.js +20424 -5052
- package/dist/live.d.ts +149 -0
- package/dist/live.js +739 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/pure.d.ts +401 -0
- package/dist/pure.js +24 -0
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +392 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +439 -0
- package/dist/sw.d.ts +207 -0
- package/dist/sw.js +393 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +477 -0
- package/dist/types.d.ts +2084 -82
- package/dist/worker-edges.js +498 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +48 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +39 -8
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +186 -0
- package/skills/sp00ky-core/SKILL.md +44 -8
- package/skills/sp00ky-core/references/config.md +8 -2
- package/src/boot/auth-flip.saga.test.ts +174 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +203 -0
- package/src/boot/boot.saga.ts +146 -0
- package/src/boot/bucket-switch.saga.test.ts +191 -0
- package/src/boot/bucket-switch.saga.ts +151 -0
- package/src/boot/preload.saga.test.ts +96 -0
- package/src/boot/preload.saga.ts +45 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/client/bucket-handle.test.ts +195 -0
- package/src/client/bucket-handle.ts +372 -0
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/router.test.ts +59 -0
- package/src/client/router.ts +104 -0
- package/src/client/runtime.test.ts +319 -0
- package/src/client/runtime.ts +307 -0
- package/src/client/services.test.ts +74 -0
- package/src/client/services.ts +440 -0
- package/src/client/sp00ky-client.test.ts +570 -0
- package/src/client/sp00ky-client.ts +875 -0
- package/src/index.ts +87 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +94 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +181 -0
- package/src/kernel/events.ts +60 -0
- package/src/kernel/interpreter.test.ts +133 -0
- package/src/kernel/interpreter.ts +151 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/live/index.test.ts +512 -0
- package/src/live/index.ts +1059 -0
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +209 -0
- package/src/modules/auth/auth.local-first.test.ts +228 -0
- package/src/modules/auth/auth.session-recheck.test.ts +140 -0
- package/src/modules/auth/events/index.ts +7 -1
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +209 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +516 -34
- package/src/modules/channel/channel.test.ts +752 -0
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +1497 -0
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +472 -0
- package/src/modules/crdt/acceptance.ts +75 -0
- package/src/modules/crdt/bytes.ts +50 -0
- package/src/modules/crdt/crdt-field.ts +82 -238
- package/src/modules/crdt/crdt.test.ts +546 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +740 -271
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/crdt/mirror.ts +37 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +661 -99
- package/src/modules/devtools/mutations.test.ts +92 -0
- package/src/modules/devtools/mutations.ts +160 -0
- package/src/modules/devtools/notify-throttle.test.ts +166 -0
- package/src/modules/devtools/state-shape.test.ts +263 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +169 -0
- package/src/modules/devtools/versions.ts +29 -0
- package/src/modules/feature-flag/index.test.ts +179 -1
- package/src/modules/feature-flag/index.ts +117 -10
- package/src/modules/ref-tables.test.ts +28 -1
- package/src/modules/ref-tables.ts +23 -1
- package/src/modules/web-push/index.test.ts +824 -0
- package/src/modules/web-push/index.ts +1027 -0
- package/src/mutation/ingest-outage.integration.test.ts +400 -0
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/mutation/mutation-id.test.ts +37 -0
- package/src/mutation/mutation-id.ts +35 -0
- package/src/mutation/pending-writes.integration.test.ts +175 -0
- package/src/mutation/push.saga.test.ts +361 -0
- package/src/mutation/push.saga.ts +245 -0
- package/src/mutation/rows.test.ts +278 -0
- package/src/mutation/rows.ts +515 -0
- package/src/mutation/tray.saga.test.ts +63 -0
- package/src/mutation/tray.saga.ts +48 -0
- package/src/mutation/write.saga.test.ts +436 -0
- package/src/mutation/write.saga.ts +384 -0
- package/src/pure.ts +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +531 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +65 -0
- package/src/query/fetch.saga.test.ts +199 -0
- package/src/query/fetch.saga.ts +120 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/query/id-set-plan.test.ts +132 -0
- package/src/query/lifecycle.saga.test.ts +274 -0
- package/src/query/lifecycle.saga.ts +186 -0
- package/src/query/list-ref-live.integration.test.ts +203 -0
- package/src/query/materialize.saga.test.ts +216 -0
- package/src/query/materialize.saga.ts +83 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +133 -0
- package/src/query/membership.saga.test.ts +514 -0
- package/src/query/membership.saga.ts +339 -0
- package/src/query/membership.test.ts +151 -0
- package/src/query/membership.ts +234 -0
- package/src/query/register.saga.test.ts +430 -0
- package/src/query/register.saga.ts +330 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/session-guard.integration.test.ts +304 -0
- package/src/query/sql.test.ts +118 -0
- package/src/query/sql.ts +174 -0
- package/src/{modules/data → query}/window-query.test.ts +22 -4
- package/src/{modules/data → query}/window-query.ts +86 -8
- package/src/services/blobs/blob-cache.test.ts +359 -0
- package/src/services/blobs/blob-cache.ts +603 -0
- package/src/services/blobs/blob-manifest.ts +227 -0
- package/src/services/blobs/blob-store.test.ts +77 -0
- package/src/services/blobs/blob-store.ts +359 -0
- package/src/services/blobs/blob.fixture.ts +90 -0
- package/src/services/blobs/index.ts +70 -0
- package/src/services/database/cache-engine.ts +223 -0
- package/src/services/database/connection-supervisor.test.ts +318 -0
- package/src/services/database/connection-supervisor.ts +422 -0
- package/src/services/database/database.query-timeout.test.ts +140 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +151 -56
- package/src/services/database/engine-factory.ts +40 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/index.ts +8 -0
- package/src/services/database/landed-body-clear.integration.test.ts +236 -0
- package/src/services/database/local-migrator.integration.test.ts +110 -0
- package/src/services/database/local-migrator.ts +54 -9
- package/src/services/database/local.test.ts +117 -0
- package/src/services/database/local.ts +364 -74
- package/src/services/database/plan-render.test.ts +159 -0
- package/src/services/database/plan-render.ts +108 -0
- package/src/services/database/relation-resolver.test.ts +484 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +283 -4
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +649 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1422 -0
- package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
- package/src/services/database/sqlite-column-reset.ts +91 -0
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
- package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
- package/src/services/database/sqlite-lock-verify.test.ts +33 -0
- package/src/services/database/sqlite-lock-verify.ts +45 -0
- package/src/services/database/sqlite-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +164 -0
- package/src/services/database/sqlite-plan-sql.ts +196 -0
- package/src/services/database/sqlite-projection.test.ts +121 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +261 -0
- package/src/services/database/sqlite-select.ts +131 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +231 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +417 -0
- package/src/services/database/surreal-cache-engine.ts +163 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +187 -6
- package/src/services/persistence/surrealdb.ts +2 -2
- package/src/services/stream-processor/index.ts +621 -93
- package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
- package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/wasm-types.ts +41 -1
- package/src/services/tabs/broker-client.ts +284 -0
- package/src/services/tabs/broker.test.ts +381 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +646 -0
- package/src/services/tabs/fake-ports.fixture.ts +112 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +262 -0
- package/src/services/tabs/support.ts +38 -0
- package/src/services/tabs/tabs-broker-worker.ts +652 -0
- package/src/sp00ky.ts +5 -648
- package/src/state/client-state.ts +231 -0
- package/src/state/lifecycle.test.ts +184 -0
- package/src/state/lifecycle.ts +127 -0
- package/src/state/reducers.test.ts +337 -0
- package/src/state/reducers.ts +571 -0
- package/src/state/selectors.test.ts +203 -0
- package/src/state/selectors.ts +264 -0
- package/src/sw/index.test.ts +582 -0
- package/src/sw/index.ts +607 -0
- package/src/sw/store.ts +96 -0
- package/src/sync/connection.saga.test.ts +97 -0
- package/src/sync/connection.saga.ts +89 -0
- package/src/sync/live.saga.test.ts +229 -0
- package/src/sync/live.saga.ts +116 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
- package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +78 -0
- package/src/sync/tabs.saga.ts +96 -0
- package/src/testing/adapters.ts +137 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +63 -0
- package/src/testing/run-pure.test.ts +92 -0
- package/src/testing/run-pure.ts +128 -0
- package/src/testing/services.ts +17 -0
- package/src/types.ts +601 -25
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +57 -0
- package/src/utils/error-classification.test.ts +116 -0
- package/src/utils/error-classification.ts +74 -0
- package/src/utils/index.ts +58 -3
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +62 -1
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/sha256.ts +15 -0
- package/src/utils/surql.ts +17 -15
- package/src/utils/utils.test.ts +3 -2
- package/tsdown.config.ts +105 -4
- package/vitest.config.ts +52 -0
- package/src/modules/cache/index.ts +0 -253
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/crdt/crdt-hydration.test.ts +0 -206
- package/src/modules/data/data.status.test.ts +0 -108
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -1491
- package/src/modules/sync/engine.ts +0 -227
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.ts +0 -90
- package/src/modules/sync/queue/queue-up.ts +0 -224
- package/src/modules/sync/scheduler.ts +0 -121
- package/src/modules/sync/sync.ts +0 -1244
- package/src/sp00ky.auth-order.test.ts +0 -65
|
@@ -0,0 +1,1497 @@
|
|
|
1
|
+
import type { ColumnSchema, QueryPlan, SchemaStructure, WhereComparison, WhereNode } from '@spooky-sync/query-builder';
|
|
2
|
+
import { RecordId } from 'surrealdb';
|
|
3
|
+
import type { Logger } from '../../services/logger/index';
|
|
4
|
+
import { encodeRecordId, parseRecordIdString } from '../../utils/index';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Peer to peer channels (`-- @channel` tables, `client.channel(query, peers)`).
|
|
8
|
+
*
|
|
9
|
+
* A channel is a filter (the `where` of one or more queries on `@channel`
|
|
10
|
+
* tables) plus the users it connects to. Writes to rows that match the
|
|
11
|
+
* filter reach the users' tabs straight over the transport (WebRTC by
|
|
12
|
+
* default), and their tabs fold them in before the database has seen them.
|
|
13
|
+
* The filter is evaluated here, in plain JS, against the row; the query is
|
|
14
|
+
* never registered. Optimistic writes, distributed:
|
|
15
|
+
*
|
|
16
|
+
* - Updates: persistent fields still go through the normal outbox. A peer
|
|
17
|
+
* shows the sent value until its own synced row catches up to it, or for
|
|
18
|
+
* `confirmTimeoutMs` at most, so a value the server rejected (or that a
|
|
19
|
+
* peer made up) falls back to the server's on its own.
|
|
20
|
+
* - `-- @ephemeral` fields never reach the database. They live in memory,
|
|
21
|
+
* last writer wins, and a peer's values vanish when it disconnects.
|
|
22
|
+
* - Creates go into the peer's store and circuit like its own optimistic
|
|
23
|
+
* create (minus the outbox); deletes hide the row. Both are undone unless
|
|
24
|
+
* the server confirms them (see the peer sagas in `mutation/write.saga.ts`).
|
|
25
|
+
*
|
|
26
|
+
* Nothing here enforces permissions beyond identity: the transport proves
|
|
27
|
+
* which user a peer is (the database stamps the signaling rows), a message
|
|
28
|
+
* is only taken from a user listed by an open channel whose filter the row
|
|
29
|
+
* matches, and fields must exist and fit their column type. Everything else
|
|
30
|
+
* is the app's call, through `channels.accept`.
|
|
31
|
+
*
|
|
32
|
+
* Update and ephemeral values are folded into subscription output only,
|
|
33
|
+
* never into the local store.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
export type Row = Record<string, unknown>;
|
|
37
|
+
|
|
38
|
+
/** Hybrid logical clock: wall ms, counter, tab peer id. Orders every write. */
|
|
39
|
+
export type Hlc = readonly [ms: number, counter: number, peer: string];
|
|
40
|
+
|
|
41
|
+
export const compareHlc = (a: Hlc, b: Hlc): number =>
|
|
42
|
+
a[0] - b[0] || a[1] - b[1] || (a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0);
|
|
43
|
+
|
|
44
|
+
/** One tab of one user. */
|
|
45
|
+
export interface PeerRef {
|
|
46
|
+
readonly user: string;
|
|
47
|
+
readonly peer: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const peerKey = (p: PeerRef): string => `${p.user}#${p.peer}`;
|
|
51
|
+
|
|
52
|
+
/** What a message does to its row. */
|
|
53
|
+
export type ChannelOpKind = 'update' | 'create' | 'delete';
|
|
54
|
+
|
|
55
|
+
/** The one message channels exchange: a write to one row. */
|
|
56
|
+
export interface ChannelMessage {
|
|
57
|
+
readonly t: 'op';
|
|
58
|
+
/** Absent means `update` (a field patch). */
|
|
59
|
+
readonly kind?: ChannelOpKind;
|
|
60
|
+
readonly table: string;
|
|
61
|
+
readonly id: string;
|
|
62
|
+
/** Wire-encoded values (see `encodeValue`): the patch, the whole row for a create, `{}` for a delete. */
|
|
63
|
+
readonly patch: Record<string, unknown>;
|
|
64
|
+
readonly hlc: Hlc;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** How a channel is doing, as `useChannel(...).status()` shows it. */
|
|
68
|
+
export type ChannelStatus = 'idle' | 'connecting' | 'connected' | 'failed' | 'unsupported';
|
|
69
|
+
|
|
70
|
+
export interface ChannelState {
|
|
71
|
+
readonly status: ChannelStatus;
|
|
72
|
+
/** Users with at least one tab connected. */
|
|
73
|
+
readonly peers: ReadonlyArray<string>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
/** What an `accept` rule decides on. */
|
|
78
|
+
export interface ChannelOp {
|
|
79
|
+
readonly kind: ChannelOpKind;
|
|
80
|
+
/** The sending user, as the database proved it. */
|
|
81
|
+
readonly from: string;
|
|
82
|
+
readonly table: string;
|
|
83
|
+
readonly id: string;
|
|
84
|
+
/** The row as this client currently shows it, overlay included; undefined for a create. */
|
|
85
|
+
readonly row: Row | undefined;
|
|
86
|
+
/** Decoded field values: the patch, the new row for a create, `{}` for a delete. */
|
|
87
|
+
readonly patch: Readonly<Row>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export type ChannelAcceptRule = (op: ChannelOp) => boolean;
|
|
91
|
+
|
|
92
|
+
// ---- transport -------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
export interface TransportHooks {
|
|
95
|
+
/** This tab, or null while signed out. */
|
|
96
|
+
self(): PeerRef | null;
|
|
97
|
+
onMessage(from: PeerRef, message: unknown): void;
|
|
98
|
+
onPeer(peer: PeerRef, up: boolean): void;
|
|
99
|
+
/** Per user: an attempt is running, a tab is connected, or attempts failed. */
|
|
100
|
+
onStatus(user: string, status: 'connecting' | 'connected' | 'failed'): void;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Moves messages between tabs. WebRTC by default; an app that already has a
|
|
105
|
+
* room (LiveKit, its own relay) can plug that in. `send` is fire and forget.
|
|
106
|
+
*/
|
|
107
|
+
export interface ChannelTransport {
|
|
108
|
+
readonly supported: boolean;
|
|
109
|
+
/** Users this tab wants connections to: the union over open channels. */
|
|
110
|
+
want(users: ReadonlySet<string>): void;
|
|
111
|
+
send(to: PeerRef, message: ChannelWire): void;
|
|
112
|
+
close(): void;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export type ChannelTransportFactory = (hooks: TransportHooks) => ChannelTransport;
|
|
116
|
+
|
|
117
|
+
/** Which rows of a table are shared: all of them, or the ones a test passes. */
|
|
118
|
+
export type ChannelShareRule = boolean | ((row: Row) => boolean);
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Sharing optimistic writes with the user's own other devices (see
|
|
122
|
+
* `ChannelsConfig.share`). Needs `ChannelsConfig.relay`.
|
|
123
|
+
*/
|
|
124
|
+
export interface ChannelShareConfig {
|
|
125
|
+
/**
|
|
126
|
+
* Per table: `true` shares every row, a function only the rows it returns
|
|
127
|
+
* true for (asked on the device that writes, and again on the one that
|
|
128
|
+
* receives). A table left out, or set to `false`, is never shared. The
|
|
129
|
+
* table needs no `-- @channel` mark: these writes only ever reach devices
|
|
130
|
+
* signed in as the same user.
|
|
131
|
+
*/
|
|
132
|
+
tables: Record<string, ChannelShareRule>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Where the room relay (`sp00ky-relay`) is, and how to use it. */
|
|
136
|
+
export interface ChannelRelayConfig {
|
|
137
|
+
/** Its WebSocket address, e.g. `wss://relay.example.com/room`. */
|
|
138
|
+
url: string;
|
|
139
|
+
/**
|
|
140
|
+
* Two browsers alone in a room also open a direct WebRTC link and talk over
|
|
141
|
+
* that while it is up. `false` keeps everything on the relay. Default true.
|
|
142
|
+
*/
|
|
143
|
+
direct?: boolean;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface ChannelsConfig {
|
|
147
|
+
/**
|
|
148
|
+
* Per table: decide whether to apply a peer's update. Runs after the
|
|
149
|
+
* built-in checks (sender listed by an open channel carrying the table,
|
|
150
|
+
* fields exist and fit).
|
|
151
|
+
* Without a rule every such update is applied.
|
|
152
|
+
*/
|
|
153
|
+
accept?: Record<string, ChannelAcceptRule>;
|
|
154
|
+
/** STUN/TURN servers for the default WebRTC transport. */
|
|
155
|
+
iceServers?: RTCIceServer[];
|
|
156
|
+
/** Replace the WebRTC transport. */
|
|
157
|
+
transport?: ChannelTransportFactory;
|
|
158
|
+
/** How long a peer's persistent value shows without the server confirming it. Default 5000. */
|
|
159
|
+
confirmTimeoutMs?: number;
|
|
160
|
+
/**
|
|
161
|
+
* The room relay this user's devices meet on: its address, or an object
|
|
162
|
+
* with more. One socket per browser, whatever the number of tabs.
|
|
163
|
+
*/
|
|
164
|
+
relay?: string | ChannelRelayConfig;
|
|
165
|
+
/**
|
|
166
|
+
* Send this user's optimistic writes straight to their other devices, so a
|
|
167
|
+
* change made on the phone shows on the laptop before the server has seen
|
|
168
|
+
* it. Off unless set, and per table. The devices tell each other which
|
|
169
|
+
* rows their open queries can show, and a write nobody shows is not sent.
|
|
170
|
+
*/
|
|
171
|
+
share?: ChannelShareConfig;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---- pure helpers ----------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
const isRecordIdLike = (v: unknown): v is RecordId<string> =>
|
|
177
|
+
v instanceof RecordId ||
|
|
178
|
+
(v !== null && typeof v === 'object' && (v as { constructor?: { name?: string } }).constructor?.name === 'RecordId');
|
|
179
|
+
|
|
180
|
+
/** `table:id` for a record id in any spelling, or null. */
|
|
181
|
+
export function idKey(v: unknown): string | null {
|
|
182
|
+
if (typeof v === 'string') return v.includes(':') ? v : null;
|
|
183
|
+
if (isRecordIdLike(v)) return encodeRecordId(v);
|
|
184
|
+
if (v !== null && typeof v === 'object' && 'table' in v && 'id' in v) {
|
|
185
|
+
const t = (v as { table: unknown }).table;
|
|
186
|
+
const name = typeof t === 'string' ? t : (t as { name?: unknown })?.name;
|
|
187
|
+
if (typeof name === 'string') return `${name}:${String((v as { id: unknown }).id)}`;
|
|
188
|
+
}
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const toBase64 = (bytes: Uint8Array): string => {
|
|
193
|
+
let s = '';
|
|
194
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
195
|
+
return btoa(s);
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const fromBase64 = (b64: string): Uint8Array => {
|
|
199
|
+
const s = atob(b64);
|
|
200
|
+
const out = new Uint8Array(s.length);
|
|
201
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
202
|
+
return out;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/** JSON-safe form of a field value: record ids, dates and bytes are tagged. */
|
|
206
|
+
export function encodeValue(v: unknown): unknown {
|
|
207
|
+
if (v === undefined) return null;
|
|
208
|
+
if (isRecordIdLike(v)) return { $rid: encodeRecordId(v) };
|
|
209
|
+
if (v instanceof Date) return { $date: v.toISOString() };
|
|
210
|
+
if (v instanceof Uint8Array) return { $bytes: toBase64(v) };
|
|
211
|
+
if (v instanceof ArrayBuffer) return { $bytes: toBase64(new Uint8Array(v)) };
|
|
212
|
+
if (Array.isArray(v)) return v.map(encodeValue);
|
|
213
|
+
if (v !== null && typeof v === 'object') {
|
|
214
|
+
const out: Row = {};
|
|
215
|
+
for (const [k, x] of Object.entries(v)) out[k] = encodeValue(x);
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
return v;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function decodeValue(v: unknown): unknown {
|
|
222
|
+
if (Array.isArray(v)) return v.map(decodeValue);
|
|
223
|
+
if (v === null || typeof v !== 'object') return v;
|
|
224
|
+
const o = v as Row;
|
|
225
|
+
const keys = Object.keys(o);
|
|
226
|
+
if (keys.length === 1) {
|
|
227
|
+
if (typeof o.$rid === 'string') return parseRecordIdString(o.$rid);
|
|
228
|
+
if (typeof o.$date === 'string') return new Date(o.$date);
|
|
229
|
+
if (typeof o.$bytes === 'string') return fromBase64(o.$bytes);
|
|
230
|
+
}
|
|
231
|
+
const out: Row = {};
|
|
232
|
+
for (const [k, x] of Object.entries(o)) out[k] = decodeValue(x);
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const sameValue = (a: unknown, b: unknown): boolean =>
|
|
237
|
+
a === b || JSON.stringify(encodeValue(a)) === JSON.stringify(encodeValue(b));
|
|
238
|
+
|
|
239
|
+
/** A well-formed `op` message, or null. */
|
|
240
|
+
export function parseMessage(raw: unknown): ChannelMessage | null {
|
|
241
|
+
if (raw === null || typeof raw !== 'object') return null;
|
|
242
|
+
const m = raw as Record<string, unknown>;
|
|
243
|
+
const hlc = m.hlc as unknown[];
|
|
244
|
+
if (m.kind !== undefined && m.kind !== 'update' && m.kind !== 'create' && m.kind !== 'delete') return null;
|
|
245
|
+
if (
|
|
246
|
+
m.t !== 'op' ||
|
|
247
|
+
typeof m.table !== 'string' ||
|
|
248
|
+
typeof m.id !== 'string' ||
|
|
249
|
+
m.patch === null ||
|
|
250
|
+
typeof m.patch !== 'object' ||
|
|
251
|
+
Array.isArray(m.patch) ||
|
|
252
|
+
!Array.isArray(hlc) ||
|
|
253
|
+
hlc.length !== 3 ||
|
|
254
|
+
typeof hlc[0] !== 'number' ||
|
|
255
|
+
typeof hlc[1] !== 'number' ||
|
|
256
|
+
typeof hlc[2] !== 'string'
|
|
257
|
+
) {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
return m as unknown as ChannelMessage;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Whether a decoded value fits a column, loosely (the shapes the client itself writes). */
|
|
264
|
+
export function fitsColumn(col: ColumnSchema, v: unknown): boolean {
|
|
265
|
+
if (v === null || v === undefined) return col.optional;
|
|
266
|
+
if (col.array) return Array.isArray(v) && v.every((x) => fitsScalar(col, x));
|
|
267
|
+
return fitsScalar(col, v);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function fitsScalar(col: ColumnSchema, v: unknown): boolean {
|
|
271
|
+
if (col.recordId) return typeof v === 'string' || isRecordIdLike(v);
|
|
272
|
+
if (col.dateTime) return v instanceof Date || typeof v === 'string';
|
|
273
|
+
switch (col.type) {
|
|
274
|
+
case 'string':
|
|
275
|
+
return typeof v === 'string';
|
|
276
|
+
case 'number':
|
|
277
|
+
return typeof v === 'number' && Number.isFinite(v);
|
|
278
|
+
case 'boolean':
|
|
279
|
+
return typeof v === 'boolean';
|
|
280
|
+
case 'Uint8Array':
|
|
281
|
+
return v instanceof Uint8Array;
|
|
282
|
+
case 'null':
|
|
283
|
+
return v === null;
|
|
284
|
+
default:
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Why a peer patch is refused against the table's columns, or null when it fits. */
|
|
290
|
+
export function checkPatch(columns: Record<string, ColumnSchema>, patch: Row, allowEmpty = false): string | null {
|
|
291
|
+
const fields = Object.keys(patch);
|
|
292
|
+
if (fields.length === 0 && !allowEmpty) return 'empty patch';
|
|
293
|
+
for (const field of fields) {
|
|
294
|
+
if (field === 'id') return 'patches the id';
|
|
295
|
+
const col = columns[field];
|
|
296
|
+
if (!col) return `unknown field '${field}'`;
|
|
297
|
+
if (col.crdt) return `'${field}' is a @crdt field`;
|
|
298
|
+
if (!fitsColumn(col, patch[field])) return `'${field}' does not fit its column type`;
|
|
299
|
+
}
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** A patch split into the fields the database gets and the ones only peers get. */
|
|
304
|
+
export function splitPatch(
|
|
305
|
+
columns: Record<string, ColumnSchema>,
|
|
306
|
+
data: Row
|
|
307
|
+
): { persistent: Row; ephemeral: Row | null } {
|
|
308
|
+
let ephemeral: Row | null = null;
|
|
309
|
+
const persistent: Row = {};
|
|
310
|
+
for (const [k, v] of Object.entries(data)) {
|
|
311
|
+
if (columns[k]?.ephemeral) (ephemeral ??= {})[k] = v;
|
|
312
|
+
else persistent[k] = v;
|
|
313
|
+
}
|
|
314
|
+
return { persistent, ephemeral };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** One overlaid field: the value, who wrote it and when. */
|
|
318
|
+
export interface OverlayEntry {
|
|
319
|
+
readonly value: unknown;
|
|
320
|
+
readonly hlc: Hlc;
|
|
321
|
+
/** `peerKey` of the author, or 'self'. */
|
|
322
|
+
readonly from: string;
|
|
323
|
+
readonly ephemeral: boolean;
|
|
324
|
+
/** When a persistent peer value stops showing; null for ephemeral and own values. */
|
|
325
|
+
readonly expiresAt: number | null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export type Overlay = ReadonlyMap<string, ReadonlyMap<string, OverlayEntry>>;
|
|
329
|
+
|
|
330
|
+
const OVERLAY_DEPTH = 4;
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Rows with the overlay folded in, nested related rows included. Untouched
|
|
334
|
+
* rows (and the array itself, when nothing changed) keep their identity.
|
|
335
|
+
*/
|
|
336
|
+
export function applyOverlay(rows: ReadonlyArray<Row>, overlay: Overlay): Row[] {
|
|
337
|
+
if (overlay.size === 0) return rows as Row[];
|
|
338
|
+
const out = foldArray(rows, overlay, 0);
|
|
339
|
+
return out as Row[];
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function foldArray(arr: ReadonlyArray<unknown>, overlay: Overlay, depth: number): ReadonlyArray<unknown> {
|
|
343
|
+
let changed = false;
|
|
344
|
+
const next = arr.map((x) => {
|
|
345
|
+
const y = foldValue(x, overlay, depth);
|
|
346
|
+
if (y !== x) changed = true;
|
|
347
|
+
return y;
|
|
348
|
+
});
|
|
349
|
+
return changed ? next : arr;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function foldValue(v: unknown, overlay: Overlay, depth: number): unknown {
|
|
353
|
+
if (depth > OVERLAY_DEPTH || v === null || typeof v !== 'object') return v;
|
|
354
|
+
if (Array.isArray(v)) return foldArray(v, overlay, depth + 1);
|
|
355
|
+
if (isRecordIdLike(v) || v instanceof Date || v instanceof Uint8Array) return v;
|
|
356
|
+
const row = v as Row;
|
|
357
|
+
let next: Row | null = null;
|
|
358
|
+
for (const [k, x] of Object.entries(row)) {
|
|
359
|
+
if (k === 'id') continue;
|
|
360
|
+
const y = foldValue(x, overlay, depth + 1);
|
|
361
|
+
if (y !== x) (next ??= { ...row })[k] = y;
|
|
362
|
+
}
|
|
363
|
+
const key = 'id' in row ? idKey(row.id) : null;
|
|
364
|
+
const fields = key ? overlay.get(key) : undefined;
|
|
365
|
+
if (fields) {
|
|
366
|
+
for (const [field, entry] of fields) {
|
|
367
|
+
if (!sameValue(row[field], entry.value)) (next ??= { ...row })[field] = entry.value;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return next ?? row;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Every record id in rows, nested related rows included. */
|
|
374
|
+
export function collectIds(rows: ReadonlyArray<unknown>, into = new Set<string>(), depth = 0): Set<string> {
|
|
375
|
+
if (depth > OVERLAY_DEPTH) return into;
|
|
376
|
+
for (const v of rows) {
|
|
377
|
+
if (v === null || typeof v !== 'object') continue;
|
|
378
|
+
if (Array.isArray(v)) {
|
|
379
|
+
collectIds(v, into, depth + 1);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
if (isRecordIdLike(v) || v instanceof Date || v instanceof Uint8Array) continue;
|
|
383
|
+
const row = v as Row;
|
|
384
|
+
const key = 'id' in row ? idKey(row.id) : null;
|
|
385
|
+
if (key) into.add(key);
|
|
386
|
+
for (const [k, x] of Object.entries(row)) {
|
|
387
|
+
if (k !== 'id' && x !== null && typeof x === 'object') collectIds([x], into, depth + 1);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return into;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Normalized peer ids, without `self`. */
|
|
394
|
+
export function peerUsers(peers: Iterable<unknown>, self: string | null): Set<string> {
|
|
395
|
+
const out = new Set<string>();
|
|
396
|
+
for (const p of peers) {
|
|
397
|
+
const key = idKey(p);
|
|
398
|
+
if (key && key !== self) out.add(key);
|
|
399
|
+
}
|
|
400
|
+
return out;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** What a channel carries: the rows of one `@channel` table its filter matches. */
|
|
404
|
+
export interface ChannelScope {
|
|
405
|
+
readonly table: string;
|
|
406
|
+
readonly where: ReadonlyArray<WhereNode>;
|
|
407
|
+
/** A further test on the row (a share rule given as a function). */
|
|
408
|
+
readonly test?: (row: Row) => boolean;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const OPS: Record<string, (a: unknown, b: unknown) => boolean> = {
|
|
412
|
+
'=': (a, b) => sameKey(a, b),
|
|
413
|
+
'==': (a, b) => sameKey(a, b),
|
|
414
|
+
'!=': (a, b) => !sameKey(a, b),
|
|
415
|
+
'>': (a, b) => order(a, b) > 0,
|
|
416
|
+
'>=': (a, b) => order(a, b) >= 0,
|
|
417
|
+
'<': (a, b) => order(a, b) < 0,
|
|
418
|
+
'<=': (a, b) => order(a, b) <= 0,
|
|
419
|
+
IN: (a, b) => Array.isArray(b) && b.some((x) => sameKey(a, x)),
|
|
420
|
+
INSIDE: (a, b) => Array.isArray(b) && b.some((x) => sameKey(a, x)),
|
|
421
|
+
'∈': (a, b) => Array.isArray(b) && b.some((x) => sameKey(a, x)),
|
|
422
|
+
'NOT IN': (a, b) => !(Array.isArray(b) && b.some((x) => sameKey(a, x))),
|
|
423
|
+
NOTINSIDE: (a, b) => !(Array.isArray(b) && b.some((x) => sameKey(a, x))),
|
|
424
|
+
'∉': (a, b) => !(Array.isArray(b) && b.some((x) => sameKey(a, x))),
|
|
425
|
+
CONTAINS: (a, b) => Array.isArray(a) && a.some((x) => sameKey(x, b)),
|
|
426
|
+
'∋': (a, b) => Array.isArray(a) && a.some((x) => sameKey(x, b)),
|
|
427
|
+
CONTAINSNOT: (a, b) => !(Array.isArray(a) && a.some((x) => sameKey(x, b))),
|
|
428
|
+
'∌': (a, b) => !(Array.isArray(a) && a.some((x) => sameKey(x, b))),
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
/** A comparable form: record ids by `table:id` (in any spelling), dates by ms. */
|
|
432
|
+
function keyOf(v: unknown): unknown {
|
|
433
|
+
if (v === undefined) return null;
|
|
434
|
+
if (isRecordIdLike(v)) return idKey(v);
|
|
435
|
+
if (v instanceof Date) return v.getTime();
|
|
436
|
+
return v;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function sameKey(a: unknown, b: unknown): boolean {
|
|
440
|
+
const x = isRecordIdLike(a) || isRecordIdLike(b) ? keyOfId(a) : keyOf(a);
|
|
441
|
+
const y = isRecordIdLike(a) || isRecordIdLike(b) ? keyOfId(b) : keyOf(b);
|
|
442
|
+
if (x === y) return true;
|
|
443
|
+
return x !== null && y !== null && typeof x === 'object' && typeof y === 'object' && sameValue(x, y);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** A record id compared against a string spelling of one. */
|
|
447
|
+
function keyOfId(v: unknown): unknown {
|
|
448
|
+
return typeof v === 'string' ? v : keyOf(v);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function order(a: unknown, b: unknown): number {
|
|
452
|
+
const x = keyOf(a) as number | string | null;
|
|
453
|
+
const y = keyOf(b) as number | string | null;
|
|
454
|
+
if (x === null || y === null || typeof x !== typeof y) return Number.NaN;
|
|
455
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function pathValue(row: Row, path: string): unknown {
|
|
459
|
+
let v: unknown = row;
|
|
460
|
+
for (const part of path.split('.')) {
|
|
461
|
+
if (v === null || typeof v !== 'object') return undefined;
|
|
462
|
+
v = (v as Row)[part];
|
|
463
|
+
}
|
|
464
|
+
return v;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function matchesComparison(c: WhereComparison, row: Row): boolean {
|
|
468
|
+
const field = pathValue(row, c.field);
|
|
469
|
+
const op = OPS[c.op];
|
|
470
|
+
return c.swap ? op(c.value, field) : op(field, c.value);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Whether `row` passes a query's `where` (a conjunction of comparisons and `_or` groups). */
|
|
474
|
+
export function matchesWhere(where: ReadonlyArray<WhereNode>, row: Row): boolean {
|
|
475
|
+
return where.every((node) => ('or' in node ? node.or.some((c) => matchesComparison(c, row)) : matchesComparison(node, row)));
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* The parts of a channel query that do nothing there (a channel only reads
|
|
480
|
+
* the `where`). Not an error, worth a warning unless `.ignoreUnusedArgs()`.
|
|
481
|
+
*/
|
|
482
|
+
export function unusedArgs(plan: QueryPlan, isOne = false): string[] {
|
|
483
|
+
const out: string[] = [];
|
|
484
|
+
if (isOne) out.push('.one()');
|
|
485
|
+
if (plan.orderBy && plan.orderBy.length > 0) out.push('orderBy');
|
|
486
|
+
if (plan.limit !== undefined && !(isOne && plan.limit === 1)) out.push('limit');
|
|
487
|
+
if (plan.offset !== undefined) out.push('offset');
|
|
488
|
+
if (plan.select && plan.select.length > 0) out.push('select');
|
|
489
|
+
return out;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* A query plan as a channel scope, or an error saying why it cannot be one:
|
|
494
|
+
* the table must be `@channel`, and the filter must be decidable from the
|
|
495
|
+
* row alone (its own fields, literal values, supported operators). Order,
|
|
496
|
+
* limit and projection do not matter to a channel and are ignored.
|
|
497
|
+
*/
|
|
498
|
+
export function compileScope(schema: SchemaStructure, plan: QueryPlan): ChannelScope {
|
|
499
|
+
const table = schema.tables.find((t) => t.name === plan.table);
|
|
500
|
+
if (!table?.channel) {
|
|
501
|
+
throw new Error(
|
|
502
|
+
`Cannot open a channel on '${plan.table}': the table is not marked '-- @channel'. ` +
|
|
503
|
+
`Add '-- @channel' above 'DEFINE TABLE ${plan.table}' and run 'spky generate'.`
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
if (plan.relations && plan.relations.length > 0) {
|
|
507
|
+
throw new Error(`A channel query on '${plan.table}' cannot use .related(): its filter must be decidable from the row alone.`);
|
|
508
|
+
}
|
|
509
|
+
const where = plan.where ?? [];
|
|
510
|
+
for (const node of where) {
|
|
511
|
+
for (const c of 'or' in node ? node.or : [node]) {
|
|
512
|
+
if (!(c.op in OPS)) throw new Error(`A channel query on '${plan.table}' cannot use the operator '${c.op}'.`);
|
|
513
|
+
if (c.value === undefined && c.paramRef) {
|
|
514
|
+
throw new Error(`A channel query on '${plan.table}' cannot compare '${c.field}' with a parameter ($${c.paramRef}); use a value.`);
|
|
515
|
+
}
|
|
516
|
+
const root = c.field.split('.')[0];
|
|
517
|
+
if (c.field.includes('.') && table.columns[root]?.recordId) {
|
|
518
|
+
throw new Error(
|
|
519
|
+
`A channel query on '${plan.table}' cannot filter on '${c.field}': it follows a record link, which the row alone does not hold.`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return { table: plan.table, where };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// ---- interest: what a device's open queries can show -------------------------------
|
|
528
|
+
|
|
529
|
+
/** One query's claim on a table: the rows its filter passes, or (`null`) all of them. */
|
|
530
|
+
export interface QueryInterest {
|
|
531
|
+
readonly table: string;
|
|
532
|
+
readonly where: ReadonlyArray<WhereNode> | null;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Per table: `true` for every row, else the filters of the queries on it. A table left out shows nothing. */
|
|
536
|
+
export type Interest = Readonly<Record<string, true | ReadonlyArray<ReadonlyArray<WhereNode>>>>;
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* A device telling its user's other devices what it shows, so they do not
|
|
540
|
+
* send it writes it has no use for. `all`: everything (it could not say more).
|
|
541
|
+
* Only ever exchanged between devices of one user.
|
|
542
|
+
*/
|
|
543
|
+
export interface InterestMessage {
|
|
544
|
+
readonly t: 'interest';
|
|
545
|
+
readonly all?: true;
|
|
546
|
+
/** Per table `true` or a list of filters, their values wire-encoded (see `encodeValue`). */
|
|
547
|
+
readonly v?: Record<string, unknown>;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** Everything a transport carries. */
|
|
551
|
+
export type ChannelWire = ChannelMessage | InterestMessage;
|
|
552
|
+
|
|
553
|
+
/** Past this many filters on one table a device just asks for all of it: the message stays small. */
|
|
554
|
+
const MAX_INTEREST_FILTERS = 24;
|
|
555
|
+
|
|
556
|
+
const knownOp = (op: unknown): op is string => typeof op === 'string' && Object.prototype.hasOwnProperty.call(OPS, op);
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* A `where` as a test the row alone decides, parameters filled in. `null`
|
|
560
|
+
* when it cannot be one (an operator this file does not evaluate, a path
|
|
561
|
+
* through a record link, a parameter without a value): then the query counts
|
|
562
|
+
* as showing the whole table, which only costs a few messages too many.
|
|
563
|
+
*/
|
|
564
|
+
function rowFilter(
|
|
565
|
+
columns: Record<string, ColumnSchema> | undefined,
|
|
566
|
+
where: ReadonlyArray<WhereNode>,
|
|
567
|
+
params: Readonly<Record<string, unknown>>
|
|
568
|
+
): WhereNode[] | null {
|
|
569
|
+
const out: WhereNode[] = [];
|
|
570
|
+
for (const node of where) {
|
|
571
|
+
const resolved: WhereComparison[] = [];
|
|
572
|
+
for (const c of 'or' in node ? node.or : [node]) {
|
|
573
|
+
if (!knownOp(c.op)) return null;
|
|
574
|
+
if (c.field.includes('.') && columns?.[c.field.split('.')[0]]?.recordId) return null;
|
|
575
|
+
let value = c.value;
|
|
576
|
+
if (value === undefined && c.paramRef) {
|
|
577
|
+
if (!(c.paramRef in params)) return null;
|
|
578
|
+
value = params[c.paramRef];
|
|
579
|
+
}
|
|
580
|
+
resolved.push(c.swap ? { field: c.field, op: c.op, value, swap: true } : { field: c.field, op: c.op, value });
|
|
581
|
+
}
|
|
582
|
+
out.push('or' in node ? { or: resolved } : resolved[0]);
|
|
583
|
+
}
|
|
584
|
+
return out;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* What a registered query can show: the rows of its own table that pass its
|
|
589
|
+
* filter, and every row of the tables it reads through `.related()` (which
|
|
590
|
+
* children it shows depends on the parents, not on the child row alone).
|
|
591
|
+
* Order, limit and offset are ignored: a row inside the filter and outside
|
|
592
|
+
* the window is sent and then not shown.
|
|
593
|
+
*/
|
|
594
|
+
export function queryInterest(
|
|
595
|
+
columnsOf: (table: string) => Record<string, ColumnSchema> | undefined,
|
|
596
|
+
plan: QueryPlan,
|
|
597
|
+
params: Readonly<Record<string, unknown>> = {}
|
|
598
|
+
): QueryInterest[] {
|
|
599
|
+
const out: QueryInterest[] = [{ table: plan.table, where: plan.ids ? null : rowFilter(columnsOf(plan.table), plan.where ?? [], params) }];
|
|
600
|
+
const walk = (relations: QueryPlan['relations']): void => {
|
|
601
|
+
for (const r of relations ?? []) {
|
|
602
|
+
out.push({ table: r.table, where: null });
|
|
603
|
+
walk(r.relations);
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
walk(plan.relations);
|
|
607
|
+
return out;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The interests of every open subscription as one, for the tables `shared`
|
|
612
|
+
* names. `'all'` once one of them is unknown. Each filter once and in a fixed
|
|
613
|
+
* order, so the same set of queries always reads the same.
|
|
614
|
+
*/
|
|
615
|
+
export function mergeInterest(list: Iterable<ReadonlyArray<QueryInterest> | null>, shared: (table: string) => boolean): Interest | 'all' {
|
|
616
|
+
const tables = new Map<string, true | Map<string, ReadonlyArray<WhereNode>>>();
|
|
617
|
+
for (const queries of list) {
|
|
618
|
+
if (queries === null) return 'all';
|
|
619
|
+
for (const q of queries) {
|
|
620
|
+
if (!shared(q.table)) continue;
|
|
621
|
+
const cur = tables.get(q.table);
|
|
622
|
+
if (cur === true) continue;
|
|
623
|
+
if (q.where === null || q.where.length === 0) {
|
|
624
|
+
tables.set(q.table, true);
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
const filters = cur ?? new Map<string, ReadonlyArray<WhereNode>>();
|
|
628
|
+
filters.set(JSON.stringify(encodeWhere(q.where)), q.where);
|
|
629
|
+
tables.set(q.table, filters.size > MAX_INTEREST_FILTERS ? true : filters);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
const out: Record<string, true | ReadonlyArray<WhereNode>[]> = {};
|
|
633
|
+
for (const [table, filters] of [...tables].sort(([a], [b]) => (a < b ? -1 : 1))) {
|
|
634
|
+
out[table] = filters === true ? true : [...filters].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, where]) => where);
|
|
635
|
+
}
|
|
636
|
+
return out;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const encodeComparison = (c: WhereComparison): unknown =>
|
|
640
|
+
c.swap ? { field: c.field, op: c.op, value: encodeValue(c.value), swap: true } : { field: c.field, op: c.op, value: encodeValue(c.value) };
|
|
641
|
+
|
|
642
|
+
function encodeWhere(where: ReadonlyArray<WhereNode>): unknown[] {
|
|
643
|
+
return where.map((n) => ('or' in n ? { or: n.or.map(encodeComparison) } : encodeComparison(n)));
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
export function encodeInterest(interest: Interest | 'all'): InterestMessage {
|
|
647
|
+
if (interest === 'all') return { t: 'interest', all: true };
|
|
648
|
+
const v: Record<string, unknown> = {};
|
|
649
|
+
for (const [table, filters] of Object.entries(interest)) {
|
|
650
|
+
v[table] = filters === true ? true : filters.map(encodeWhere);
|
|
651
|
+
}
|
|
652
|
+
return { t: 'interest', v };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function decodeComparison(raw: unknown): WhereComparison | null {
|
|
656
|
+
if (raw === null || typeof raw !== 'object') return null;
|
|
657
|
+
const c = raw as Record<string, unknown>;
|
|
658
|
+
if (typeof c.field !== 'string' || !knownOp(c.op)) return null;
|
|
659
|
+
return c.swap === true ? { field: c.field, op: c.op, value: decodeValue(c.value), swap: true } : { field: c.field, op: c.op, value: decodeValue(c.value) };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* A peer's interest message, or `null` when it is not one. A filter this
|
|
664
|
+
* side cannot read turns its table into "all of it": never into less than
|
|
665
|
+
* the peer asked for.
|
|
666
|
+
*/
|
|
667
|
+
export function decodeInterest(raw: unknown): Interest | 'all' | null {
|
|
668
|
+
if (raw === null || typeof raw !== 'object' || (raw as { t?: unknown }).t !== 'interest') return null;
|
|
669
|
+
const m = raw as { all?: unknown; v?: unknown };
|
|
670
|
+
if (m.all === true) return 'all';
|
|
671
|
+
if (m.v === null || typeof m.v !== 'object' || Array.isArray(m.v)) return null;
|
|
672
|
+
const out: Record<string, true | WhereNode[][]> = {};
|
|
673
|
+
for (const [table, filters] of Object.entries(m.v as Record<string, unknown>)) {
|
|
674
|
+
if (!Array.isArray(filters)) {
|
|
675
|
+
if (filters === true) out[table] = true;
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const decoded: WhereNode[][] = [];
|
|
679
|
+
let readable = filters.length <= MAX_INTEREST_FILTERS;
|
|
680
|
+
for (const where of readable ? filters : []) {
|
|
681
|
+
if (!Array.isArray(where)) {
|
|
682
|
+
readable = false;
|
|
683
|
+
break;
|
|
684
|
+
}
|
|
685
|
+
const nodes: WhereNode[] = [];
|
|
686
|
+
for (const n of where) {
|
|
687
|
+
const group = n !== null && typeof n === 'object' && Array.isArray((n as { or?: unknown }).or) ? (n as { or: unknown[] }).or : null;
|
|
688
|
+
const list = (group ?? [n]).map(decodeComparison);
|
|
689
|
+
if (list.includes(null) || list.length === 0) {
|
|
690
|
+
readable = false;
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
693
|
+
nodes.push(group ? { or: list as WhereComparison[] } : (list[0] as WhereComparison));
|
|
694
|
+
}
|
|
695
|
+
if (!readable) break;
|
|
696
|
+
decoded.push(nodes);
|
|
697
|
+
}
|
|
698
|
+
out[table] = readable ? decoded : true;
|
|
699
|
+
}
|
|
700
|
+
return out;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** Whether a device with this interest can show one of `rows` (a row before and after a write) of `table`. */
|
|
704
|
+
export function showsRow(interest: Interest | 'all', table: string, rows: ReadonlyArray<Row>): boolean {
|
|
705
|
+
if (interest === 'all') return true;
|
|
706
|
+
const filters = interest[table];
|
|
707
|
+
if (filters === undefined) return false;
|
|
708
|
+
return filters === true || filters.some((where) => rows.some((r) => matchesWhere(where, r)));
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// ---- manager ---------------------------------------------------------------------
|
|
712
|
+
|
|
713
|
+
interface Tap {
|
|
714
|
+
readonly cb: (rows: Row[]) => void;
|
|
715
|
+
raw: Row[] | null;
|
|
716
|
+
/** Every record id in `raw`, computed on first need. */
|
|
717
|
+
ids: Set<string> | null;
|
|
718
|
+
/** What its query can show, or null when nobody said. */
|
|
719
|
+
readonly interest: ReadonlyArray<QueryInterest> | null;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
interface Channel {
|
|
723
|
+
scopes: ReadonlyArray<ChannelScope>;
|
|
724
|
+
/** Peers as given, kept so a sign-in can drop the new self from them. */
|
|
725
|
+
listed: unknown[];
|
|
726
|
+
users: Set<string>;
|
|
727
|
+
readonly listeners: Set<(s: ChannelState) => void>;
|
|
728
|
+
state: ChannelState;
|
|
729
|
+
closed: boolean;
|
|
730
|
+
/** The one channel to the user's own other devices (`channels.share`): its only user is whoever is signed in. */
|
|
731
|
+
readonly own?: boolean;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** An open channel. `client.channel(...)` wraps it with scoped writes. */
|
|
735
|
+
export interface ChannelHandle {
|
|
736
|
+
/** The tables its queries read. */
|
|
737
|
+
tables(): ReadonlyArray<string>;
|
|
738
|
+
state(): ChannelState;
|
|
739
|
+
/** Called at once with the current state, then on every change. */
|
|
740
|
+
subscribe(cb: (s: ChannelState) => void): () => void;
|
|
741
|
+
/** Replace who it connects to (your own id is skipped). */
|
|
742
|
+
setPeers(peers: Iterable<unknown>): void;
|
|
743
|
+
/** Replace what it carries (the queries' filters changed). */
|
|
744
|
+
setScopes(scopes: ReadonlyArray<ChannelScope>): void;
|
|
745
|
+
close(): void;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** How peers' creates and deletes reach the store (the runtime's peer sagas). */
|
|
749
|
+
export interface ChannelRows {
|
|
750
|
+
/** Insert a peer's row, unconfirmed for `ttlMs`. False when refused. */
|
|
751
|
+
create(table: string, id: string, row: Row, ttlMs: number): Promise<boolean>;
|
|
752
|
+
/** Hide a row a peer deleted (or undo its unconfirmed create). False when there was nothing to do. */
|
|
753
|
+
delete(table: string, id: string, ttlMs: number): Promise<boolean>;
|
|
754
|
+
/** The row as the local store holds it, or null. What a filter is checked against. */
|
|
755
|
+
read(id: string): Promise<Row | null>;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
export interface ChannelManagerDeps {
|
|
759
|
+
config?: ChannelsConfig;
|
|
760
|
+
/** Without it, peers' creates and deletes are ignored. */
|
|
761
|
+
rows?: ChannelRows;
|
|
762
|
+
logger?: Pick<Logger, 'debug' | 'warn'>;
|
|
763
|
+
/** Builds the transport the first time a channel has peers. */
|
|
764
|
+
transport?: ChannelTransportFactory;
|
|
765
|
+
now?: () => number;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const SWEEP_MS = 1000;
|
|
769
|
+
|
|
770
|
+
const randomPeerId = (): string => {
|
|
771
|
+
const bytes = new Uint8Array(8);
|
|
772
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
773
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
export class ChannelManager {
|
|
777
|
+
private readonly tables: Map<string, { columns: Record<string, ColumnSchema>; channel: boolean }>;
|
|
778
|
+
private readonly schema: SchemaStructure;
|
|
779
|
+
private readonly overlay = new Map<string, Map<string, OverlayEntry>>();
|
|
780
|
+
private readonly taps = new Set<Tap>();
|
|
781
|
+
private readonly channels = new Set<Channel>();
|
|
782
|
+
private readonly handles = new WeakMap<ChannelHandle, Channel>();
|
|
783
|
+
private readonly connected = new Map<string, PeerRef>();
|
|
784
|
+
private readonly userStatus = new Map<string, 'connecting' | 'connected' | 'failed'>();
|
|
785
|
+
/** Unused-argument warnings already given, so a reactive query does not repeat them. */
|
|
786
|
+
private readonly warnedUnused = new Set<string>();
|
|
787
|
+
private readonly peerId = randomPeerId();
|
|
788
|
+
/** `channels.share`: the rule per shared table, and the channel that carries them to the user's own devices. */
|
|
789
|
+
private readonly shared = new Map<string, ChannelShareRule>();
|
|
790
|
+
private readonly ownChannel: Channel | null = null;
|
|
791
|
+
/** What each of the user's other tabs said it shows, by `peerKey`. A tab that said nothing gets everything. */
|
|
792
|
+
private readonly interest = new Map<string, Interest | 'all'>();
|
|
793
|
+
/** The interest message last sent, so an unchanged one is not sent again. */
|
|
794
|
+
private announced: string | null = null;
|
|
795
|
+
private announcing = false;
|
|
796
|
+
private user: string | null = null;
|
|
797
|
+
private clock: Hlc;
|
|
798
|
+
private transport: ChannelTransport | null = null;
|
|
799
|
+
private sweepTimer: ReturnType<typeof setInterval> | null = null;
|
|
800
|
+
private closed = false;
|
|
801
|
+
private readonly now: () => number;
|
|
802
|
+
private readonly confirmMs: number;
|
|
803
|
+
|
|
804
|
+
constructor(
|
|
805
|
+
schema: SchemaStructure,
|
|
806
|
+
private readonly deps: ChannelManagerDeps = {}
|
|
807
|
+
) {
|
|
808
|
+
this.schema = schema;
|
|
809
|
+
for (const [table, rule] of Object.entries(deps.config?.share?.tables ?? {})) {
|
|
810
|
+
if (rule === false || rule === undefined) continue;
|
|
811
|
+
if (!schema.tables.some((t) => t.name === table)) {
|
|
812
|
+
deps.logger?.warn({ table, Category: 'sp00ky-client::channel' }, `channels.share names '${table}', which is not a table of the schema`);
|
|
813
|
+
continue;
|
|
814
|
+
}
|
|
815
|
+
this.shared.set(table, rule);
|
|
816
|
+
}
|
|
817
|
+
// A shared table takes peer writes like a `@channel` one. It needs no mark
|
|
818
|
+
// in the schema: its writes only reach devices of the same user.
|
|
819
|
+
this.tables = new Map(schema.tables.map((t) => [t.name, { columns: t.columns, channel: t.channel === true || this.shared.has(t.name) }]));
|
|
820
|
+
this.now = deps.now ?? Date.now;
|
|
821
|
+
this.confirmMs = Math.max(0, deps.config?.confirmTimeoutMs ?? 5000);
|
|
822
|
+
this.clock = [0, 0, this.peerId];
|
|
823
|
+
if (this.shared.size > 0) {
|
|
824
|
+
this.ownChannel = {
|
|
825
|
+
scopes: [...this.shared].map(([table, rule]) => (typeof rule === 'function' ? { table, where: [], test: safeTest(rule) } : { table, where: [] })),
|
|
826
|
+
listed: [],
|
|
827
|
+
users: new Set(),
|
|
828
|
+
listeners: new Set(),
|
|
829
|
+
state: { status: 'idle', peers: [] },
|
|
830
|
+
closed: false,
|
|
831
|
+
own: true,
|
|
832
|
+
};
|
|
833
|
+
this.channels.add(this.ownChannel);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** True when any table is a channel table or shared; otherwise the client skips all of this. */
|
|
838
|
+
get enabled(): boolean {
|
|
839
|
+
for (const t of this.tables.values()) if (t.channel) return true;
|
|
840
|
+
return false;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** Whether the user's own devices are part of this (`channels.share` names a table). */
|
|
844
|
+
get sharing(): boolean {
|
|
845
|
+
return this.ownChannel !== null;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** How the user's own devices are doing (`channels.share`): `idle` when nothing is shared or nobody is signed in. */
|
|
849
|
+
ownState(): ChannelState {
|
|
850
|
+
return this.ownChannel?.state ?? { status: 'idle', peers: [] };
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/** Called at once with the state of the link to the user's own devices, then on every change. */
|
|
854
|
+
subscribeOwn(cb: (s: ChannelState) => void): () => void {
|
|
855
|
+
const ch = this.ownChannel;
|
|
856
|
+
cb(this.ownState());
|
|
857
|
+
if (!ch) return () => {};
|
|
858
|
+
ch.listeners.add(cb);
|
|
859
|
+
return () => void ch.listeners.delete(cb);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** What a registered query can show, as `tap` takes it. */
|
|
863
|
+
interestOf(plan: QueryPlan | undefined, params?: Readonly<Record<string, unknown>>): QueryInterest[] | null {
|
|
864
|
+
return plan ? queryInterest((table) => this.tables.get(table)?.columns, plan, params) : null;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** The signed-in user changed: peers, their values and the transport start over. */
|
|
868
|
+
setUser(user: string | null): void {
|
|
869
|
+
if (user === this.user) return;
|
|
870
|
+
this.user = user;
|
|
871
|
+
this.transport?.close();
|
|
872
|
+
this.transport = null;
|
|
873
|
+
this.connected.clear();
|
|
874
|
+
this.userStatus.clear();
|
|
875
|
+
this.interest.clear();
|
|
876
|
+
this.announced = null;
|
|
877
|
+
const touched = new Set(this.overlay.keys());
|
|
878
|
+
this.overlay.clear();
|
|
879
|
+
for (const ch of this.channels) ch.users = ch.own ? new Set(user ? [user] : []) : peerUsers(ch.listed, user);
|
|
880
|
+
this.syncWanted();
|
|
881
|
+
this.emitFor(touched);
|
|
882
|
+
this.notifyAll();
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/**
|
|
886
|
+
* Compile a query plan into a channel scope (throws when it cannot be
|
|
887
|
+
* one). Parts the channel ignores draw one warning per distinct query
|
|
888
|
+
* shape, unless the query says so itself (`ignoreUnused`).
|
|
889
|
+
*/
|
|
890
|
+
scope(plan: QueryPlan, opts: { isOne?: boolean; ignoreUnused?: boolean } = {}): ChannelScope {
|
|
891
|
+
const scope = compileScope(this.schema, plan);
|
|
892
|
+
const unused = opts.ignoreUnused ? [] : unusedArgs(plan, opts.isOne);
|
|
893
|
+
if (unused.length > 0) {
|
|
894
|
+
const message =
|
|
895
|
+
`channel query on '${plan.table}' has ${unused.join(', ')}, which a channel ignores (it only uses the where filter). ` +
|
|
896
|
+
`Remove them, or add .ignoreUnusedArgs() to the query to say it is on purpose.`;
|
|
897
|
+
if (!this.warnedUnused.has(message)) {
|
|
898
|
+
this.warnedUnused.add(message);
|
|
899
|
+
this.deps.logger?.warn({ table: plan.table, unused, Category: 'sp00ky-client::channel' }, message);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
return scope;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** Open a channel carrying the rows `scopes` match to `peers`. */
|
|
906
|
+
open(scopes: ReadonlyArray<ChannelScope>, peers: Iterable<unknown>): ChannelHandle {
|
|
907
|
+
if (scopes.length === 0) throw new Error('A channel needs at least one query.');
|
|
908
|
+
const listed = [...peers];
|
|
909
|
+
const ch: Channel = {
|
|
910
|
+
scopes,
|
|
911
|
+
listed,
|
|
912
|
+
users: peerUsers(listed, this.user),
|
|
913
|
+
listeners: new Set(),
|
|
914
|
+
state: { status: 'idle', peers: [] },
|
|
915
|
+
closed: false,
|
|
916
|
+
};
|
|
917
|
+
this.channels.add(ch);
|
|
918
|
+
this.syncWanted();
|
|
919
|
+
ch.state = this.stateOf(ch);
|
|
920
|
+
const handle: ChannelHandle = {
|
|
921
|
+
tables: () => [...new Set(ch.scopes.map((sc) => sc.table))],
|
|
922
|
+
state: () => ch.state,
|
|
923
|
+
subscribe: (cb) => {
|
|
924
|
+
cb(ch.state);
|
|
925
|
+
ch.listeners.add(cb);
|
|
926
|
+
return () => ch.listeners.delete(cb);
|
|
927
|
+
},
|
|
928
|
+
setPeers: (next) => {
|
|
929
|
+
if (ch.closed) return;
|
|
930
|
+
ch.listed = [...next];
|
|
931
|
+
ch.users = peerUsers(ch.listed, this.user);
|
|
932
|
+
this.syncWanted();
|
|
933
|
+
this.notify(ch);
|
|
934
|
+
},
|
|
935
|
+
setScopes: (next) => {
|
|
936
|
+
if (ch.closed) return;
|
|
937
|
+
if (next.length === 0) throw new Error('A channel needs at least one query.');
|
|
938
|
+
ch.scopes = next;
|
|
939
|
+
},
|
|
940
|
+
close: () => {
|
|
941
|
+
if (ch.closed) return;
|
|
942
|
+
ch.closed = true;
|
|
943
|
+
this.channels.delete(ch);
|
|
944
|
+
ch.listeners.clear();
|
|
945
|
+
this.syncWanted();
|
|
946
|
+
},
|
|
947
|
+
};
|
|
948
|
+
this.handles.set(handle, ch);
|
|
949
|
+
return handle;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/** Throws unless `handle` is an open channel of this manager with a query on `table`. */
|
|
953
|
+
assertCarries(handle: ChannelHandle, table: string): void {
|
|
954
|
+
const ch = this.handles.get(handle);
|
|
955
|
+
if (!ch || ch.closed) throw new Error('This channel is closed.');
|
|
956
|
+
if (!ch.scopes.some((sc) => sc.table === table)) {
|
|
957
|
+
throw new Error(`This channel has no query on '${table}' (it reads ${[...new Set(ch.scopes.map((sc) => sc.table))].join(', ')}).`);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/**
|
|
962
|
+
* Follow a subscription: `feed` it the raw rows, and `cb` gets them with
|
|
963
|
+
* the overlay folded in, again whenever the overlay changes for its rows.
|
|
964
|
+
*/
|
|
965
|
+
tap(cb: (rows: Row[]) => void, interest: ReadonlyArray<QueryInterest> | null = null): { feed: (rows: Row[]) => void; stop: () => void } {
|
|
966
|
+
const tap: Tap = { cb, raw: null, ids: null, interest };
|
|
967
|
+
this.taps.add(tap);
|
|
968
|
+
this.announceSoon();
|
|
969
|
+
return {
|
|
970
|
+
feed: (rows) => {
|
|
971
|
+
tap.raw = rows;
|
|
972
|
+
tap.ids = null;
|
|
973
|
+
this.emit(tap);
|
|
974
|
+
},
|
|
975
|
+
stop: () => {
|
|
976
|
+
if (this.taps.delete(tap)) this.announceSoon();
|
|
977
|
+
},
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** Split an own write on `table` into database fields and peer-only fields. */
|
|
982
|
+
split(table: string, data: Row): { persistent: Row; ephemeral: Row | null } {
|
|
983
|
+
const t = this.tables.get(table);
|
|
984
|
+
if (!t?.channel) return { persistent: data, ephemeral: null };
|
|
985
|
+
return splitPatch(t.columns, data);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* An own update: ephemeral fields go into the overlay (they have no other
|
|
990
|
+
* home), persistent fields drop any peer value they supersede, and the
|
|
991
|
+
* whole patch goes to the peers (of `scope`, or of the channel carrying the
|
|
992
|
+
* table, see `targets`).
|
|
993
|
+
*/
|
|
994
|
+
local(table: string, id: string, persistent: Row, ephemeral: Row | null, scope?: ChannelHandle): void {
|
|
995
|
+
const t = this.tables.get(table);
|
|
996
|
+
if (!t?.channel || this.closed) return;
|
|
997
|
+
const rid = normalizeId(table, id);
|
|
998
|
+
const hlc = this.tick();
|
|
999
|
+
const fields = this.overlay.get(rid);
|
|
1000
|
+
let touched = false;
|
|
1001
|
+
if (fields) {
|
|
1002
|
+
for (const f of Object.keys(persistent)) touched = fields.delete(f) || touched;
|
|
1003
|
+
}
|
|
1004
|
+
if (ephemeral) {
|
|
1005
|
+
const map = fields ?? new Map<string, OverlayEntry>();
|
|
1006
|
+
for (const [f, value] of Object.entries(ephemeral)) {
|
|
1007
|
+
map.set(f, { value, hlc, from: 'self', ephemeral: true, expiresAt: null });
|
|
1008
|
+
}
|
|
1009
|
+
this.overlay.set(rid, map);
|
|
1010
|
+
touched = true;
|
|
1011
|
+
}
|
|
1012
|
+
if (fields && fields.size === 0) this.overlay.delete(rid);
|
|
1013
|
+
if (touched) this.emitFor(new Set([rid]));
|
|
1014
|
+
const patch = { ...persistent, ...(ephemeral ?? {}) };
|
|
1015
|
+
if (Object.keys(patch).length === 0) return;
|
|
1016
|
+
// Sent if the row matches before or after the patch, so a row moving
|
|
1017
|
+
// out of a channel's filter still reaches its peers.
|
|
1018
|
+
void this.rowFor(rid).then((row) => {
|
|
1019
|
+
const after = { ...(row ?? { id: rid }), ...patch };
|
|
1020
|
+
const rows = row ? [row, after] : [after];
|
|
1021
|
+
this.send(this.targets(table, rows, scope), table, rid, patch, hlc, 'update', rows);
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* An own create: its ephemeral fields go into the overlay (the store never
|
|
1027
|
+
* holds them), and the whole row goes to the peers.
|
|
1028
|
+
*/
|
|
1029
|
+
localCreate(table: string, id: string, row: Row, scope?: ChannelHandle): void {
|
|
1030
|
+
const t = this.tables.get(table);
|
|
1031
|
+
if (!t?.channel || this.closed) return;
|
|
1032
|
+
const rid = normalizeId(table, id);
|
|
1033
|
+
const full = pickColumns(t.columns, row);
|
|
1034
|
+
const hlc = this.tick();
|
|
1035
|
+
const ephemeral = Object.keys(full).filter((f) => t.columns[f]?.ephemeral);
|
|
1036
|
+
if (ephemeral.length > 0) {
|
|
1037
|
+
const map = this.overlay.get(rid) ?? new Map<string, OverlayEntry>();
|
|
1038
|
+
for (const f of ephemeral) map.set(f, { value: full[f], hlc, from: 'self', ephemeral: true, expiresAt: null });
|
|
1039
|
+
this.overlay.set(rid, map);
|
|
1040
|
+
this.emitFor(new Set([rid]));
|
|
1041
|
+
}
|
|
1042
|
+
const rows = [{ ...full, id: rid }];
|
|
1043
|
+
this.send(this.targets(table, rows, scope), table, rid, full, hlc, 'create', rows);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* An own delete: the peers hide the row at once. Resolves once it is sent;
|
|
1048
|
+
* await it before the local delete, which the filter check reads past.
|
|
1049
|
+
*/
|
|
1050
|
+
async localDelete(table: string, id: string, scope?: ChannelHandle): Promise<void> {
|
|
1051
|
+
const t = this.tables.get(table);
|
|
1052
|
+
if (!t?.channel || this.closed) return;
|
|
1053
|
+
const rid = normalizeId(table, id);
|
|
1054
|
+
const hlc = this.tick();
|
|
1055
|
+
const row = await this.rowFor(rid);
|
|
1056
|
+
if (row) this.send(this.targets(table, [row], scope), table, rid, {}, hlc, 'delete', [row]);
|
|
1057
|
+
if (this.overlay.delete(rid)) this.emitFor(new Set([rid]));
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/** A transport delivered a message from `from`. */
|
|
1061
|
+
receive(from: PeerRef, raw: unknown): void {
|
|
1062
|
+
if (this.closed) return;
|
|
1063
|
+
if (raw !== null && typeof raw === 'object' && (raw as { t?: unknown }).t === 'interest') return this.receiveInterest(from, raw);
|
|
1064
|
+
const msg = parseMessage(raw);
|
|
1065
|
+
if (!msg) return this.drop(from, 'malformed message');
|
|
1066
|
+
this.observe(msg.hlc);
|
|
1067
|
+
const t = this.tables.get(msg.table);
|
|
1068
|
+
if (!t?.channel) return this.drop(from, `'${msg.table}' is not a @channel table`);
|
|
1069
|
+
const rid = normalizeId(msg.table, msg.id);
|
|
1070
|
+
if (rid.slice(0, rid.indexOf(':')) !== msg.table) return this.drop(from, 'id is not a row of the table');
|
|
1071
|
+
if (!this.listedOn(msg.table, from.user)) return this.drop(from, `no channel on '${msg.table}' lists ${from.user}`);
|
|
1072
|
+
const kind = msg.kind ?? 'update';
|
|
1073
|
+
if (kind === 'create') return this.receiveCreate(from, msg, rid, t.columns);
|
|
1074
|
+
if (kind === 'delete') return void this.receiveDelete(from, msg.table, rid);
|
|
1075
|
+
const patch: Row = {};
|
|
1076
|
+
for (const [k, v] of Object.entries(msg.patch)) patch[k] = decodeValue(v);
|
|
1077
|
+
const problem = checkPatch(t.columns, patch);
|
|
1078
|
+
if (problem) return this.drop(from, problem);
|
|
1079
|
+
void this.receiveUpdate(from, msg, rid, patch, t.columns);
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/** A peer updated a row we hold, inside a channel's filter (before or after the patch). */
|
|
1083
|
+
private async receiveUpdate(from: PeerRef, msg: ChannelMessage, rid: string, patch: Row, columns: Record<string, ColumnSchema>): Promise<void> {
|
|
1084
|
+
const row = await this.rowFor(rid);
|
|
1085
|
+
if (this.closed) return;
|
|
1086
|
+
if (!row) return this.drop(from, `${rid} is not held here, so no filter can be checked`);
|
|
1087
|
+
if (!this.matchesFor(msg.table, [row, { ...row, ...patch }], from.user)) return this.drop(from, `${rid} is outside every channel listing ${from.user}`);
|
|
1088
|
+
if (!this.accepts({ kind: 'update', from: from.user, table: msg.table, id: rid, row, patch })) {
|
|
1089
|
+
return this.drop(from, 'refused by the accept rule');
|
|
1090
|
+
}
|
|
1091
|
+
const map = this.overlay.get(rid) ?? new Map<string, OverlayEntry>();
|
|
1092
|
+
const key = peerKey(from);
|
|
1093
|
+
let touched = false;
|
|
1094
|
+
for (const [field, value] of Object.entries(patch)) {
|
|
1095
|
+
const prev = map.get(field);
|
|
1096
|
+
if (prev && compareHlc(prev.hlc, msg.hlc) >= 0) continue;
|
|
1097
|
+
const ephemeral = columns[field]?.ephemeral === true;
|
|
1098
|
+
map.set(field, { value, hlc: msg.hlc, from: key, ephemeral, expiresAt: ephemeral ? null : this.now() + this.confirmMs });
|
|
1099
|
+
touched = true;
|
|
1100
|
+
}
|
|
1101
|
+
if (map.size > 0) this.overlay.set(rid, map);
|
|
1102
|
+
if (!touched) return;
|
|
1103
|
+
this.ensureSweep();
|
|
1104
|
+
this.emitFor(new Set([rid]));
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/** A peer created a row: into the store like an own optimistic create, unconfirmed. */
|
|
1108
|
+
private receiveCreate(from: PeerRef, msg: ChannelMessage, rid: string, columns: Record<string, ColumnSchema>): void {
|
|
1109
|
+
const rows = this.deps.rows;
|
|
1110
|
+
if (!rows) return this.drop(from, 'creates are not wired');
|
|
1111
|
+
const row: Row = {};
|
|
1112
|
+
for (const [k, v] of Object.entries(msg.patch)) if (k !== 'id') row[k] = decodeValue(v);
|
|
1113
|
+
const problem = checkPatch(columns, row, true);
|
|
1114
|
+
if (problem) return this.drop(from, problem);
|
|
1115
|
+
if (!this.matchesFor(msg.table, [{ ...row, id: parseRecordIdString(rid) }], from.user)) {
|
|
1116
|
+
return this.drop(from, `the new ${rid} is outside every channel listing ${from.user}`);
|
|
1117
|
+
}
|
|
1118
|
+
if (!this.accepts({ kind: 'create', from: from.user, table: msg.table, id: rid, row: undefined, patch: row })) {
|
|
1119
|
+
return this.drop(from, 'refused by the accept rule');
|
|
1120
|
+
}
|
|
1121
|
+
const persistent: Row = {};
|
|
1122
|
+
const ephemeral: Row = {};
|
|
1123
|
+
for (const [k, v] of Object.entries(row)) (columns[k]?.ephemeral ? ephemeral : persistent)[k] = v;
|
|
1124
|
+
void rows.create(msg.table, rid, persistent, this.confirmMs).then(
|
|
1125
|
+
(applied) => {
|
|
1126
|
+
if (!applied || this.closed || Object.keys(ephemeral).length === 0) return;
|
|
1127
|
+
const map = this.overlay.get(rid) ?? new Map<string, OverlayEntry>();
|
|
1128
|
+
for (const [f, value] of Object.entries(ephemeral)) {
|
|
1129
|
+
map.set(f, { value, hlc: msg.hlc, from: peerKey(from), ephemeral: true, expiresAt: null });
|
|
1130
|
+
}
|
|
1131
|
+
this.overlay.set(rid, map);
|
|
1132
|
+
this.emitFor(new Set([rid]));
|
|
1133
|
+
},
|
|
1134
|
+
(error) => this.deps.logger?.debug({ error, Category: 'sp00ky-client::channel' }, 'peer create failed')
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/** A peer deleted a row inside a channel's filter: hide it until the server confirms (or undo its own create). */
|
|
1139
|
+
private async receiveDelete(from: PeerRef, table: string, rid: string): Promise<void> {
|
|
1140
|
+
const rows = this.deps.rows;
|
|
1141
|
+
if (!rows) return this.drop(from, 'deletes are not wired');
|
|
1142
|
+
const row = await this.rowFor(rid);
|
|
1143
|
+
if (this.closed) return;
|
|
1144
|
+
if (!row) return this.drop(from, `${rid} is not held here`);
|
|
1145
|
+
if (!this.matchesFor(table, [row], from.user)) return this.drop(from, `${rid} is outside every channel listing ${from.user}`);
|
|
1146
|
+
if (!this.accepts({ kind: 'delete', from: from.user, table, id: rid, row, patch: {} })) {
|
|
1147
|
+
return this.drop(from, 'refused by the accept rule');
|
|
1148
|
+
}
|
|
1149
|
+
if (this.overlay.delete(rid)) this.emitFor(new Set([rid]));
|
|
1150
|
+
void rows.delete(table, rid, this.confirmMs).catch((error) =>
|
|
1151
|
+
this.deps.logger?.debug({ error, Category: 'sp00ky-client::channel' }, 'peer delete failed')
|
|
1152
|
+
);
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/** One of the user's own tabs said what it shows. Anybody else's word on that is ignored. */
|
|
1156
|
+
private receiveInterest(from: PeerRef, raw: unknown): void {
|
|
1157
|
+
if (from.user !== this.user || !this.ownChannel) return this.drop(from, 'interest from another user');
|
|
1158
|
+
const interest = decodeInterest(raw);
|
|
1159
|
+
if (!interest) return this.drop(from, 'malformed interest');
|
|
1160
|
+
this.interest.set(peerKey(from), interest);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
private accepts(op: ChannelOp): boolean {
|
|
1164
|
+
const rule = this.deps.config?.accept?.[op.table];
|
|
1165
|
+
if (!rule) return true;
|
|
1166
|
+
try {
|
|
1167
|
+
return rule(op) === true;
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
this.deps.logger?.warn({ error, Category: 'sp00ky-client::channel' }, 'channel accept rule threw');
|
|
1170
|
+
return false;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/** A peer tab came up (send it our ephemeral state) or went away (drop its). */
|
|
1175
|
+
peerChanged(peer: PeerRef, up: boolean): void {
|
|
1176
|
+
const key = peerKey(peer);
|
|
1177
|
+
if (up) {
|
|
1178
|
+
this.connected.set(key, peer);
|
|
1179
|
+
this.userStatus.set(peer.user, 'connected');
|
|
1180
|
+
if (this.ownChannel && peer.user === this.user) this.transport?.send(peer, encodeInterest(this.ownInterest()));
|
|
1181
|
+
this.sendSnapshot(peer);
|
|
1182
|
+
} else {
|
|
1183
|
+
this.connected.delete(key);
|
|
1184
|
+
this.interest.delete(key);
|
|
1185
|
+
const touched = new Set<string>();
|
|
1186
|
+
for (const [rid, fields] of this.overlay) {
|
|
1187
|
+
for (const [f, e] of fields) {
|
|
1188
|
+
if (e.from === key && e.ephemeral) {
|
|
1189
|
+
fields.delete(f);
|
|
1190
|
+
touched.add(rid);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
if (fields.size === 0) this.overlay.delete(rid);
|
|
1194
|
+
}
|
|
1195
|
+
this.emitFor(touched);
|
|
1196
|
+
}
|
|
1197
|
+
this.notifyAll();
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
statusChanged(user: string, status: 'connecting' | 'connected' | 'failed'): void {
|
|
1201
|
+
if (status !== 'connected' && [...this.connected.values()].some((p) => p.user === user)) return;
|
|
1202
|
+
this.userStatus.set(user, status);
|
|
1203
|
+
this.notifyAll();
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
close(): void {
|
|
1207
|
+
this.closed = true;
|
|
1208
|
+
this.transport?.close();
|
|
1209
|
+
this.transport = null;
|
|
1210
|
+
if (this.sweepTimer) clearInterval(this.sweepTimer);
|
|
1211
|
+
this.sweepTimer = null;
|
|
1212
|
+
this.taps.clear();
|
|
1213
|
+
for (const ch of this.channels) ch.closed = true;
|
|
1214
|
+
this.channels.clear();
|
|
1215
|
+
this.overlay.clear();
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// ---- internals -----------------------------------------------------------------
|
|
1219
|
+
|
|
1220
|
+
private syncWanted(): void {
|
|
1221
|
+
if (this.closed) return;
|
|
1222
|
+
const wanted = new Set<string>();
|
|
1223
|
+
for (const ch of this.channels) for (const u of ch.users) wanted.add(u);
|
|
1224
|
+
if (!this.transport) {
|
|
1225
|
+
if (wanted.size === 0 || !this.user || !this.deps.transport) return;
|
|
1226
|
+
this.transport = this.deps.transport({
|
|
1227
|
+
self: () => (this.user ? { user: this.user, peer: this.peerId } : null),
|
|
1228
|
+
onMessage: (from, message) => this.receive(from, message),
|
|
1229
|
+
onPeer: (peer, up) => this.peerChanged(peer, up),
|
|
1230
|
+
onStatus: (user, status) => this.statusChanged(user, status),
|
|
1231
|
+
});
|
|
1232
|
+
}
|
|
1233
|
+
this.transport.want(wanted);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
/** Some open channel lists `user` and has a query on `table` (the cheap check before any read). */
|
|
1237
|
+
private listedOn(table: string, user: string): boolean {
|
|
1238
|
+
for (const ch of this.channels) if (ch.users.has(user) && ch.scopes.some((sc) => sc.table === table)) return true;
|
|
1239
|
+
return false;
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
/** Some open channel listing `user` has a query on `table` one of `rows` matches. */
|
|
1243
|
+
private matchesFor(table: string, rows: ReadonlyArray<Row>, user: string): boolean {
|
|
1244
|
+
for (const ch of this.channels) if (ch.users.has(user) && carries(ch, table, rows)) return true;
|
|
1245
|
+
return false;
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* Who an own write goes to: the peers of every open channel (or only
|
|
1250
|
+
* `scope`) whose filter one of `rows` matches. That is what keeps a
|
|
1251
|
+
* message of one conversation away from the participants of another.
|
|
1252
|
+
*/
|
|
1253
|
+
private targets(table: string, rows: ReadonlyArray<Row>, scope?: ChannelHandle): ReadonlySet<string> {
|
|
1254
|
+
const users = new Set<string>();
|
|
1255
|
+
const pick = scope ? this.handles.get(scope) : undefined;
|
|
1256
|
+
// A write made through one channel still reaches the user's own devices.
|
|
1257
|
+
for (const ch of pick ? (this.ownChannel ? [pick, this.ownChannel] : [pick]) : this.channels) {
|
|
1258
|
+
if (ch.closed || !carries(ch, table, rows)) continue;
|
|
1259
|
+
for (const u of ch.users) users.add(u);
|
|
1260
|
+
}
|
|
1261
|
+
return users;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/** The row as shown (overlay included): from a subscription, else the store. */
|
|
1265
|
+
private async rowFor(rid: string): Promise<Row | null> {
|
|
1266
|
+
const shown = this.rowOf(rid);
|
|
1267
|
+
if (shown) return shown;
|
|
1268
|
+
const stored = await this.deps.rows?.read(rid).catch(() => null);
|
|
1269
|
+
return stored ? applyOverlay([stored], this.overlay)[0] : null;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
private send(users: ReadonlySet<string>, table: string, rid: string, patch: Row, hlc: Hlc, kind: ChannelOpKind, rows: ReadonlyArray<Row>): void {
|
|
1273
|
+
const transport = this.transport;
|
|
1274
|
+
if (!transport || users.size === 0) return;
|
|
1275
|
+
const encoded: Row = {};
|
|
1276
|
+
for (const [k, v] of Object.entries(patch)) encoded[k] = encodeValue(v);
|
|
1277
|
+
const message: ChannelMessage =
|
|
1278
|
+
kind === 'update' ? { t: 'op', table, id: rid, patch: encoded, hlc } : { t: 'op', kind, table, id: rid, patch: encoded, hlc };
|
|
1279
|
+
for (const [key, peer] of this.connected) {
|
|
1280
|
+
if (!users.has(peer.user)) continue;
|
|
1281
|
+
// One of the user's own tabs that said what it shows, and it is not this
|
|
1282
|
+
// row: it has no use for the write, and the server brings it anyway.
|
|
1283
|
+
const interest = peer.user === this.user ? this.interest.get(key) : undefined;
|
|
1284
|
+
if (interest !== undefined && !showsRow(interest, table, rows)) continue;
|
|
1285
|
+
transport.send(peer, message);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/** What this tab's subscriptions show of the shared tables. */
|
|
1290
|
+
private ownInterest(): Interest | 'all' {
|
|
1291
|
+
return mergeInterest(
|
|
1292
|
+
[...this.taps].map((t) => t.interest),
|
|
1293
|
+
(table) => this.shared.has(table)
|
|
1294
|
+
);
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/** Tell the user's other tabs what this one shows, once the subscriptions of this turn are all in. */
|
|
1298
|
+
private announceSoon(): void {
|
|
1299
|
+
if (!this.ownChannel || this.announcing || this.closed) return;
|
|
1300
|
+
this.announcing = true;
|
|
1301
|
+
void Promise.resolve().then(() => {
|
|
1302
|
+
this.announcing = false;
|
|
1303
|
+
const transport = this.transport;
|
|
1304
|
+
if (this.closed || !transport || !this.user) return;
|
|
1305
|
+
const message = encodeInterest(this.ownInterest());
|
|
1306
|
+
const text = JSON.stringify(message);
|
|
1307
|
+
if (text === this.announced) return;
|
|
1308
|
+
this.announced = text;
|
|
1309
|
+
for (const peer of this.connected.values()) if (peer.user === this.user) transport.send(peer, message);
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/** Own ephemeral values of rows inside a channel a newly connected peer is listed on. */
|
|
1314
|
+
private sendSnapshot(peer: PeerRef): void {
|
|
1315
|
+
for (const [rid, fields] of this.overlay) {
|
|
1316
|
+
const own = [...fields].filter(([, e]) => e.from === 'self');
|
|
1317
|
+
if (own.length === 0) continue;
|
|
1318
|
+
const table = rid.slice(0, rid.indexOf(':'));
|
|
1319
|
+
if (!this.listedOn(table, peer.user)) continue;
|
|
1320
|
+
const patch: Row = {};
|
|
1321
|
+
let hlc = own[0][1].hlc;
|
|
1322
|
+
for (const [f, e] of own) {
|
|
1323
|
+
patch[f] = encodeValue(e.value);
|
|
1324
|
+
if (compareHlc(e.hlc, hlc) > 0) hlc = e.hlc;
|
|
1325
|
+
}
|
|
1326
|
+
void this.rowFor(rid).then((row) => {
|
|
1327
|
+
if (!row || !this.matchesFor(table, [row], peer.user)) return;
|
|
1328
|
+
this.transport?.send(peer, { t: 'op', table, id: rid, patch, hlc });
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
private rowOf(rid: string): Row | undefined {
|
|
1334
|
+
for (const tap of this.taps) {
|
|
1335
|
+
if (!tap.raw || !idsOf(tap).has(rid)) continue;
|
|
1336
|
+
const row = findRow(tap.raw, rid, 0);
|
|
1337
|
+
if (row) return applyOverlay([row], this.overlay)[0];
|
|
1338
|
+
}
|
|
1339
|
+
return undefined;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
private emit(tap: Tap): void {
|
|
1343
|
+
if (!tap.raw) return;
|
|
1344
|
+
const rows = applyOverlay(tap.raw, this.overlay);
|
|
1345
|
+
this.confirm(tap.raw);
|
|
1346
|
+
tap.cb(rows);
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
private emitFor(rids: ReadonlySet<string>): void {
|
|
1350
|
+
if (rids.size === 0) return;
|
|
1351
|
+
for (const tap of this.taps) {
|
|
1352
|
+
if (!tap.raw) continue;
|
|
1353
|
+
const ids = idsOf(tap);
|
|
1354
|
+
for (const rid of rids) {
|
|
1355
|
+
if (ids.has(rid)) {
|
|
1356
|
+
this.emit(tap);
|
|
1357
|
+
break;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
/** Persistent peer values the synced rows already hold are done showing. */
|
|
1364
|
+
private confirm(raw: ReadonlyArray<Row>): void {
|
|
1365
|
+
if (this.overlay.size === 0) return;
|
|
1366
|
+
for (const rid of collectIds(raw)) {
|
|
1367
|
+
const fields = this.overlay.get(rid);
|
|
1368
|
+
if (!fields) continue;
|
|
1369
|
+
const row = findRow(raw, rid, 0);
|
|
1370
|
+
if (!row) continue;
|
|
1371
|
+
for (const [f, e] of fields) {
|
|
1372
|
+
if (!e.ephemeral && e.from !== 'self' && f in row && sameValue(row[f], e.value)) fields.delete(f);
|
|
1373
|
+
}
|
|
1374
|
+
if (fields.size === 0) this.overlay.delete(rid);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
private ensureSweep(): void {
|
|
1379
|
+
if (this.sweepTimer || this.closed) return;
|
|
1380
|
+
this.sweepTimer = setInterval(() => this.sweep(), SWEEP_MS);
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
private sweep(): void {
|
|
1384
|
+
const now = this.now();
|
|
1385
|
+
const touched = new Set<string>();
|
|
1386
|
+
let pending = false;
|
|
1387
|
+
for (const [rid, fields] of this.overlay) {
|
|
1388
|
+
for (const [f, e] of fields) {
|
|
1389
|
+
if (e.expiresAt === null) continue;
|
|
1390
|
+
if (e.expiresAt <= now) {
|
|
1391
|
+
fields.delete(f);
|
|
1392
|
+
touched.add(rid);
|
|
1393
|
+
} else {
|
|
1394
|
+
pending = true;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
if (fields.size === 0) this.overlay.delete(rid);
|
|
1398
|
+
}
|
|
1399
|
+
if (!pending && this.sweepTimer) {
|
|
1400
|
+
clearInterval(this.sweepTimer);
|
|
1401
|
+
this.sweepTimer = null;
|
|
1402
|
+
}
|
|
1403
|
+
this.emitFor(touched);
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
private tick(): Hlc {
|
|
1407
|
+
const now = this.now();
|
|
1408
|
+
const [ms, c] = this.clock;
|
|
1409
|
+
this.clock = now > ms ? [now, 0, this.peerId] : [ms, c + 1, this.peerId];
|
|
1410
|
+
return this.clock;
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
private observe(h: Hlc): void {
|
|
1414
|
+
if (h[0] > this.clock[0] || (h[0] === this.clock[0] && h[1] > this.clock[1])) this.clock = [h[0], h[1], this.peerId];
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
private stateOf(ch: Channel): ChannelState {
|
|
1418
|
+
const users = [...ch.users];
|
|
1419
|
+
if (users.length === 0) return { status: 'idle', peers: [] };
|
|
1420
|
+
if (this.transport && !this.transport.supported) return { status: 'unsupported', peers: [] };
|
|
1421
|
+
const up = users.filter((u) => [...this.connected.values()].some((p) => p.user === u));
|
|
1422
|
+
if (up.length > 0) return { status: 'connected', peers: up };
|
|
1423
|
+
if (users.every((u) => this.userStatus.get(u) === 'failed')) return { status: 'failed', peers: [] };
|
|
1424
|
+
return { status: 'connecting', peers: [] };
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
private notify(ch: Channel): void {
|
|
1428
|
+
const next = this.stateOf(ch);
|
|
1429
|
+
if (next.status === ch.state.status && next.peers.join(',') === ch.state.peers.join(',')) return;
|
|
1430
|
+
ch.state = next;
|
|
1431
|
+
for (const cb of ch.listeners) cb(next);
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
private notifyAll(): void {
|
|
1435
|
+
for (const ch of this.channels) this.notify(ch);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
private drop(from: PeerRef, reason: string): void {
|
|
1439
|
+
this.deps.logger?.debug({ from: from.user, reason, Category: 'sp00ky-client::channel' }, 'channel message dropped');
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
/** Whether a channel has a query on `table` that one of `rows` matches. */
|
|
1444
|
+
function carries(ch: Channel, table: string, rows: ReadonlyArray<Row>): boolean {
|
|
1445
|
+
return ch.scopes.some((sc) => sc.table === table && rows.some((r) => matchesWhere(sc.where, r) && (!sc.test || sc.test(r))));
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/** A share rule that never throws: a rule that does shares nothing. */
|
|
1449
|
+
const safeTest =
|
|
1450
|
+
(rule: (row: Row) => boolean) =>
|
|
1451
|
+
(row: Row): boolean => {
|
|
1452
|
+
try {
|
|
1453
|
+
return rule(row) === true;
|
|
1454
|
+
} catch {
|
|
1455
|
+
return false;
|
|
1456
|
+
}
|
|
1457
|
+
};
|
|
1458
|
+
|
|
1459
|
+
/** The fields of `row` the table has as plain columns (no id, no `@crdt`). */
|
|
1460
|
+
function pickColumns(columns: Record<string, ColumnSchema>, row: Row): Row {
|
|
1461
|
+
const out: Row = {};
|
|
1462
|
+
for (const [k, v] of Object.entries(row)) {
|
|
1463
|
+
if (k === 'id' || !columns[k] || columns[k].crdt || v === undefined) continue;
|
|
1464
|
+
out[k] = v;
|
|
1465
|
+
}
|
|
1466
|
+
return out;
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
function idsOf(tap: Tap): Set<string> {
|
|
1470
|
+
return (tap.ids ??= tap.raw ? collectIds(tap.raw) : new Set());
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/** `table:id` for an id given with or without its table. */
|
|
1474
|
+
function normalizeId(table: string, id: string): string {
|
|
1475
|
+
return id.includes(':') ? id : `${table}:${id}`;
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
function findRow(rows: ReadonlyArray<unknown>, rid: string, depth: number): Row | null {
|
|
1479
|
+
if (depth > OVERLAY_DEPTH) return null;
|
|
1480
|
+
for (const v of rows) {
|
|
1481
|
+
if (v === null || typeof v !== 'object') continue;
|
|
1482
|
+
if (Array.isArray(v)) {
|
|
1483
|
+
const hit = findRow(v, rid, depth + 1);
|
|
1484
|
+
if (hit) return hit;
|
|
1485
|
+
continue;
|
|
1486
|
+
}
|
|
1487
|
+
if (isRecordIdLike(v) || v instanceof Date || v instanceof Uint8Array) continue;
|
|
1488
|
+
const row = v as Row;
|
|
1489
|
+
if ('id' in row && idKey(row.id) === rid) return row;
|
|
1490
|
+
for (const [k, x] of Object.entries(row)) {
|
|
1491
|
+
if (k === 'id' || x === null || typeof x !== 'object') continue;
|
|
1492
|
+
const hit = findRow([x], rid, depth + 1);
|
|
1493
|
+
if (hit) return hit;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
return null;
|
|
1497
|
+
}
|