@spooky-sync/core 1.0.0-beta.8 → 1.0.0-beta.9
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 +1 -1
- package/dist/index.d.ts +99 -2
- package/dist/index.js +942 -27
- package/dist/types.d.ts +68 -2
- package/package.json +3 -3
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/sp00ky-client.test.ts +64 -1
- package/src/client/sp00ky-client.ts +53 -10
- package/src/index.ts +7 -0
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- 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 +2 -2
- package/src/types.ts +5 -0
package/dist/types.d.ts
CHANGED
|
@@ -157,10 +157,36 @@ interface ChannelTransport {
|
|
|
157
157
|
readonly supported: boolean;
|
|
158
158
|
/** Users this tab wants connections to: the union over open channels. */
|
|
159
159
|
want(users: ReadonlySet<string>): void;
|
|
160
|
-
send(to: PeerRef, message:
|
|
160
|
+
send(to: PeerRef, message: ChannelWire): void;
|
|
161
161
|
close(): void;
|
|
162
162
|
}
|
|
163
163
|
type ChannelTransportFactory = (hooks: TransportHooks) => ChannelTransport;
|
|
164
|
+
/** Which rows of a table are shared: all of them, or the ones a test passes. */
|
|
165
|
+
type ChannelShareRule = boolean | ((row: Row$1) => boolean);
|
|
166
|
+
/**
|
|
167
|
+
* Sharing optimistic writes with the user's own other devices (see
|
|
168
|
+
* `ChannelsConfig.share`). Needs `ChannelsConfig.relay`.
|
|
169
|
+
*/
|
|
170
|
+
interface ChannelShareConfig {
|
|
171
|
+
/**
|
|
172
|
+
* Per table: `true` shares every row, a function only the rows it returns
|
|
173
|
+
* true for (asked on the device that writes, and again on the one that
|
|
174
|
+
* receives). A table left out, or set to `false`, is never shared. The
|
|
175
|
+
* table needs no `-- @channel` mark: these writes only ever reach devices
|
|
176
|
+
* signed in as the same user.
|
|
177
|
+
*/
|
|
178
|
+
tables: Record<string, ChannelShareRule>;
|
|
179
|
+
}
|
|
180
|
+
/** Where the room relay (`sp00ky-relay`) is, and how to use it. */
|
|
181
|
+
interface ChannelRelayConfig {
|
|
182
|
+
/** Its WebSocket address, e.g. `wss://relay.example.com/room`. */
|
|
183
|
+
url: string;
|
|
184
|
+
/**
|
|
185
|
+
* Two browsers alone in a room also open a direct WebRTC link and talk over
|
|
186
|
+
* that while it is up. `false` keeps everything on the relay. Default true.
|
|
187
|
+
*/
|
|
188
|
+
direct?: boolean;
|
|
189
|
+
}
|
|
164
190
|
interface ChannelsConfig {
|
|
165
191
|
/**
|
|
166
192
|
* Per table: decide whether to apply a peer's update. Runs after the
|
|
@@ -175,6 +201,18 @@ interface ChannelsConfig {
|
|
|
175
201
|
transport?: ChannelTransportFactory;
|
|
176
202
|
/** How long a peer's persistent value shows without the server confirming it. Default 5000. */
|
|
177
203
|
confirmTimeoutMs?: number;
|
|
204
|
+
/**
|
|
205
|
+
* The room relay this user's devices meet on: its address, or an object
|
|
206
|
+
* with more. One socket per browser, whatever the number of tabs.
|
|
207
|
+
*/
|
|
208
|
+
relay?: string | ChannelRelayConfig;
|
|
209
|
+
/**
|
|
210
|
+
* Send this user's optimistic writes straight to their other devices, so a
|
|
211
|
+
* change made on the phone shows on the laptop before the server has seen
|
|
212
|
+
* it. Off unless set, and per table. The devices tell each other which
|
|
213
|
+
* rows their open queries can show, and a write nobody shows is not sent.
|
|
214
|
+
*/
|
|
215
|
+
share?: ChannelShareConfig;
|
|
178
216
|
}
|
|
179
217
|
/** `table:id` for a record id in any spelling, or null. */
|
|
180
218
|
|
|
@@ -182,6 +220,8 @@ interface ChannelsConfig {
|
|
|
182
220
|
interface ChannelScope {
|
|
183
221
|
readonly table: string;
|
|
184
222
|
readonly where: ReadonlyArray<WhereNode>;
|
|
223
|
+
/** A further test on the row (a share rule given as a function). */
|
|
224
|
+
readonly test?: (row: Row$1) => boolean;
|
|
185
225
|
}
|
|
186
226
|
/** Whether `row` passes a query's `where` (a conjunction of comparisons and `_or` groups). */
|
|
187
227
|
declare function matchesWhere(where: ReadonlyArray<WhereNode>, row: Row$1): boolean;
|
|
@@ -197,6 +237,27 @@ declare function unusedArgs(plan: QueryPlan, isOne?: boolean): string[];
|
|
|
197
237
|
* limit and projection do not matter to a channel and are ignored.
|
|
198
238
|
*/
|
|
199
239
|
|
|
240
|
+
/**
|
|
241
|
+
* A device telling its user's other devices what it shows, so they do not
|
|
242
|
+
* send it writes it has no use for. `all`: everything (it could not say more).
|
|
243
|
+
* Only ever exchanged between devices of one user.
|
|
244
|
+
*/
|
|
245
|
+
interface InterestMessage {
|
|
246
|
+
readonly t: 'interest';
|
|
247
|
+
readonly all?: true;
|
|
248
|
+
/** Per table `true` or a list of filters, their values wire-encoded (see `encodeValue`). */
|
|
249
|
+
readonly v?: Record<string, unknown>;
|
|
250
|
+
}
|
|
251
|
+
/** Everything a transport carries. */
|
|
252
|
+
type ChannelWire = ChannelMessage | InterestMessage;
|
|
253
|
+
/**
|
|
254
|
+
* What a registered query can show: the rows of its own table that pass its
|
|
255
|
+
* filter, and every row of the tables it reads through `.related()` (which
|
|
256
|
+
* children it shows depends on the parents, not on the child row alone).
|
|
257
|
+
* Order, limit and offset are ignored: a row inside the filter and outside
|
|
258
|
+
* the window is sent and then not shown.
|
|
259
|
+
*/
|
|
260
|
+
|
|
200
261
|
/** An open channel. `client.channel(...)` wraps it with scoped writes. */
|
|
201
262
|
interface ChannelHandle {
|
|
202
263
|
/** The tables its queries read. */
|
|
@@ -1826,6 +1887,11 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1826
1887
|
* apply. `iceServers` configures the default WebRTC transport (a public
|
|
1827
1888
|
* STUN server when omitted; add TURN for networks that block direct
|
|
1828
1889
|
* connections), `transport` replaces it.
|
|
1890
|
+
*
|
|
1891
|
+
* `share` sends this user's optimistic writes straight to their other
|
|
1892
|
+
* devices, per table (`share: { tables: { game: true, note: (row) =>
|
|
1893
|
+
* !row.draft } }`), through the room relay named by `relay` (the
|
|
1894
|
+
* `sp00ky-relay` server, one socket per browser). Off unless set.
|
|
1829
1895
|
*/
|
|
1830
1896
|
channels?: ChannelsConfig;
|
|
1831
1897
|
/**
|
|
@@ -2431,4 +2497,4 @@ interface Sp00kyChannel<S extends SchemaStructure, T extends string> extends Omi
|
|
|
2431
2497
|
delete<N extends T>(table: N, id: string): Promise<void>;
|
|
2432
2498
|
}
|
|
2433
2499
|
//#endregion
|
|
2434
|
-
export { WebPushInfo as $,
|
|
2500
|
+
export { WebPushInfo as $, ChannelRelayConfig as $t, RecordVersionArray as A, AuthEventTypeMap as At, StorageHealthStatus as B, ImpersonationTimerHost as Bt, QueryState as C, AuthService as Ct, QueryTimings as D, SignOutContext as Dt, QueryTimeToLive as E, SIGN_OUT_HOOK_TIMEOUT_MS as Et, Sp00kyChannel as F, SealedQuery as Ft, TimingPhase as G, decodeTokenClaims as Gt, SyncHealth as H, ORIGIN_TOKEN_KEY as Ht, Sp00kyConfig as I, EventDefinition as It, PushDeviceKind as J, sameImpersonation as Jt, UpdateOptions as K, impersonationFromToken as Kt, Sp00kyQueryResult as L, EventSystem as Lt, RegistrationTimings as M, createAuthEventSystem as Mt, RunOptions as N, RemoteDatabaseService as Nt, QueryUpdateCallback as O, SignOutHook as Ot, ServerViewMeta as P, LocalStore as Pt, WebPushErrorCode as Q, ChannelOp as Qt, Sp00kyQueryResultPromise as R, IMPERSONATION_ACCESS as Rt, QueryHash as S, ActiveImpersonation as St, QueryStatusCallback as T, REFUSAL_RECHECK_MIN_MS as Tt, SyncHealthConfig as U, SESSION_POLL_MS as Ut, StoreType as V, ImpersonationTimers as Vt, SyncHealthStatus as W, TokenClaims as Wt, WebPushDevice as X, ChannelHandle as Xt, WebPushConfig as Y, ChannelAcceptRule as Yt, WebPushError as Z, ChannelMessage as Zt, PreloadOptions as _, PushPayload as _t, EventSubscriptionOptions as a, ChannelTransport as an, WebPushSyncOptions as at, QueryConfig as b, WebPushClientMessage as bt, LocalWorkers as c, ChannelsConfig as cn, WebPushUnsupportedReason as ct, MutationCallback as d, TransportHooks as dn, BridgeSignOutMessage as dt, ChannelScope as en, WebPushMessage as et, MutationEvent as f, matchesWhere as fn, BridgeTokenMessage as ft, PinoTransmit as g, PushOp as gt, PhaseStat as h, Logger$1 as hn, PushNotificationAction as ht, EdgeDelta as i, ChannelStatus as in, WebPushSupport as it, RecordVersionDiff as j, AuthEventTypes as jt, ReconnectConfig as k, AuthEventSystem as kt, MATERIALIZATION_SAMPLE_WINDOW as l, InterestMessage as ln, WebPushUpdateOptions as lt, PersistenceClient as m, LogTap as mn, PushNotification as mt, ConnectionState as n, ChannelShareRule as nn, WebPushModule as nt, InlineRow as o, ChannelTransportFactory as on, WebPushSyncStatus as ot, MutationEventType as p, unusedArgs as pn, PUSH_PAYLOAD_VERSION as pt, PUSH_ENDPOINT_KEY as q, renewDelayMs as qt, DebounceOptions as r, ChannelState as rn, WebPushSubscribeOptions as rt, Level$1 as s, ChannelWire as sn, WebPushUnsubscribeOptions as st, ChannelQuery as t, ChannelShareConfig as tn, WebPushMessageInput as tt, MembershipOutcome as u, PeerRef as un, detectWebPushSupport as ut, PreloadRefresh as v, PushPayloadKind as vt, QueryStatus as w, ImpersonationCandidate as wt, QueryConfigRecord as x, isPushPayload as xt, QueryAuthorityCallback as y, PushUrgency as yt, StorageHealth as z, ImpersonationInfo as zt };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spooky-sync/core",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.9",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": [
|
|
6
6
|
"./dist/sqlite-worker.js"
|
|
@@ -81,8 +81,8 @@
|
|
|
81
81
|
}
|
|
82
82
|
},
|
|
83
83
|
"dependencies": {
|
|
84
|
-
"@spooky-sync/query-builder": "1.0.0-beta.
|
|
85
|
-
"@spooky-sync/ssp-wasm": "1.0.0-beta.
|
|
84
|
+
"@spooky-sync/query-builder": "1.0.0-beta.9",
|
|
85
|
+
"@spooky-sync/ssp-wasm": "1.0.0-beta.9",
|
|
86
86
|
"@sqlite.org/sqlite-wasm": "3.53.0-build1",
|
|
87
87
|
"@surrealdb/wasm": "^3.1.0",
|
|
88
88
|
"@surrealdb/wasm-native": "^3.3.4",
|
|
@@ -143,6 +143,8 @@ write) and `db.discardFailedMutation(id)`.
|
|
|
143
143
|
|
|
144
144
|
On `-- @channel` tables, `client.channel(query, peers)` opens WebRTC channels to the users listed (both sides must list each other) for the rows the query's `where` matches (checked per row, never registered). Plain `client.update` / `create` / `delete` reach the peers of every open channel whose filter the row matches; the handle's own writes limit that to its peers. `-- @ephemeral` fields go only to peers. Order/limit/select/`.one()` warn unless `.ignoreUnusedArgs()`. Follow status with `ch.subscribe(cb)`, close with `ch.close()`. Config: `channels: { accept, iceServers, transport, confirmTimeoutMs }`. Docs: `/docs/client/channels`.
|
|
145
145
|
|
|
146
|
+
**Your own devices.** `channels: { relay: 'wss://relay.example.com/room', share: { tables: { game: true, note: (row) => !row.draft } } }` sends the signed-in user's optimistic writes on those tables straight to their other devices, whatever those run: the Flutter and Rust clients join the same rooms (the tables need no `-- @channel`). `relay` is the address of the `sp00ky-relay` server (`apps/relay`), which puts each socket into the room of the user its session token belongs to. One socket per browser is shared by its tabs; two browsers alone also talk over a direct WebRTC link (`relay: { url, direct: false }` turns that off). A device is only sent writes its open queries can show. `client.shareState()` / `client.subscribeShareState(cb)` report `{ status, peers }`. Off unless `share` is set.
|
|
147
|
+
|
|
146
148
|
## Authentication
|
|
147
149
|
|
|
148
150
|
See [references/auth.md](references/auth.md) for the full auth API.
|
|
@@ -6,6 +6,7 @@ import { fakeAdapters } from '../testing/adapters';
|
|
|
6
6
|
import { fakeServiceBundle } from '../testing/fake-services';
|
|
7
7
|
import { defaultEnv } from '../query/env';
|
|
8
8
|
import type { StatementResult } from '../kernel/effects';
|
|
9
|
+
import { FakeRelay, settle } from '../modules/channel/rooms.fixture';
|
|
9
10
|
|
|
10
11
|
const schema = { tables: [{ name: 'thing', columns: { a: {} } }], backends: { api: { outboxTable: 'thing', routes: { go: { args: {} } } } } } as any;
|
|
11
12
|
const config = { database: { namespace: 'n', database: 'd' }, schema, schemaSurql: '', logLevel: 'silent' } as any;
|
|
@@ -365,7 +366,7 @@ describe('Sp00kyClient facade (channels)', () => {
|
|
|
365
366
|
});
|
|
366
367
|
const runtime = new Runtime({ env: defaultEnv(chSchema, { materializeDebounceMs: 1 }), adapters: a.adapters, logger: services.logger, tabId: 'tab-test' });
|
|
367
368
|
const client = new Sp00kyClient<any>({ ...config, schema: chSchema, channels } as any, { services, runtime });
|
|
368
|
-
return { client, runtime };
|
|
369
|
+
return { client, runtime, services };
|
|
369
370
|
}
|
|
370
371
|
|
|
371
372
|
it('opens a channel, keeps ephemeral fields out of writes, scopes its own writes, and wires peer rows to the runtime', async () => {
|
|
@@ -425,4 +426,66 @@ describe('Sp00kyClient facade (channels)', () => {
|
|
|
425
426
|
ch.close();
|
|
426
427
|
await client.close();
|
|
427
428
|
});
|
|
429
|
+
|
|
430
|
+
it('shares writes with the user\'s other devices through the room relay', async () => {
|
|
431
|
+
const relay = new FakeRelay();
|
|
432
|
+
const g = globalThis as { WebSocket?: unknown };
|
|
433
|
+
const before = g.WebSocket;
|
|
434
|
+
g.WebSocket = relay.WebSocket;
|
|
435
|
+
try {
|
|
436
|
+
const channels = { relay: 'ws://relay.test/room', share: { tables: { room: true } } };
|
|
437
|
+
const phone = channelClient(channels);
|
|
438
|
+
const laptop = channelClient({ ...channels, relay: { url: 'ws://relay.test/room', direct: false } });
|
|
439
|
+
for (const device of [phone, laptop]) {
|
|
440
|
+
(device.services.remote as any).getAuthToken = () => 't-a';
|
|
441
|
+
await device.client.init();
|
|
442
|
+
(device.client as any).channels.setUser('user:a');
|
|
443
|
+
}
|
|
444
|
+
const states: string[] = [];
|
|
445
|
+
const stopStates = phone.client.subscribeShareState((s) => states.push(s.status));
|
|
446
|
+
await settle();
|
|
447
|
+
// One socket each, signed in with the session token, in the room of their user.
|
|
448
|
+
expect(relay.sockets.map((sock) => sock.sent[0])).toEqual([
|
|
449
|
+
expect.objectContaining({ t: 'hello', v: 1, token: 't-a' }),
|
|
450
|
+
expect.objectContaining({ t: 'hello', v: 1, token: 't-a' }),
|
|
451
|
+
]);
|
|
452
|
+
expect([...relay.rooms.keys()]).toEqual(['user:a']);
|
|
453
|
+
expect(phone.client.shareState()).toEqual({ status: 'connected', peers: ['user:a'] });
|
|
454
|
+
expect(states).toEqual(['connecting', 'connected']);
|
|
455
|
+
|
|
456
|
+
// The laptop shows nothing of the table yet: the write stays on the phone.
|
|
457
|
+
const ops = () => relay.sockets[0].sent.filter((f) => f.t === 'msg' && (f.d as any)?.m?.m?.t === 'op');
|
|
458
|
+
await phone.client.update('room', 'room:1', { a: 7 });
|
|
459
|
+
await settle();
|
|
460
|
+
expect(ops()).toEqual([]);
|
|
461
|
+
|
|
462
|
+
// Once a query on it is mounted there, the next write goes out.
|
|
463
|
+
const { hash } = await (laptop.client.query('room', {} as any) as any).build().run();
|
|
464
|
+
const stop = await laptop.client.subscribe(hash, () => {}, { immediate: true });
|
|
465
|
+
await settle();
|
|
466
|
+
await phone.client.update('room', 'room:1', { a: 8 });
|
|
467
|
+
await settle();
|
|
468
|
+
expect(ops().map((f) => (f.d as any).m.m)).toEqual([expect.objectContaining({ t: 'op', table: 'room', id: 'room:1', patch: { a: 8 } })]);
|
|
469
|
+
stop();
|
|
470
|
+
stopStates();
|
|
471
|
+
await phone.client.close();
|
|
472
|
+
await laptop.client.close();
|
|
473
|
+
await settle();
|
|
474
|
+
expect(relay.rooms.size).toBe(0);
|
|
475
|
+
} finally {
|
|
476
|
+
g.WebSocket = before;
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it('says so when sharing is asked for without a relay', async () => {
|
|
481
|
+
const services = fakeServiceBundle<any>();
|
|
482
|
+
const warned: string[] = [];
|
|
483
|
+
(services.logger as any).warn = (_fields: unknown, msg: string) => warned.push(msg);
|
|
484
|
+
const a = fakeAdapters({ services: { 'hint.read': () => 'u1', 'local.usesSurqlSchema': () => false, 'auth.restoreSession': async () => null, 'auth.sessionAuthId': () => null, 'remote.connect': () => new Promise(() => {}) } });
|
|
485
|
+
const runtime = new Runtime({ env: defaultEnv(chSchema, { materializeDebounceMs: 1 }), adapters: a.adapters, logger: services.logger, tabId: 'tab-test' });
|
|
486
|
+
const client = new Sp00kyClient<any>({ ...config, schema: chSchema, channels: { share: { tables: { room: true } } } } as any, { services, runtime });
|
|
487
|
+
expect(warned.filter((m) => m.includes('channels.relay'))).toHaveLength(1);
|
|
488
|
+
expect(client.shareState().status).toBe('idle');
|
|
489
|
+
await client.close();
|
|
490
|
+
});
|
|
428
491
|
});
|
|
@@ -39,8 +39,10 @@ import type { FeatureFlagOptions, FeatureFlagOverride } from '../modules/feature
|
|
|
39
39
|
import { AppReleaseModule, AppReleaseHandle } from '../modules/app-release/index';
|
|
40
40
|
import type { AppReleaseOptions } from '../modules/app-release/index';
|
|
41
41
|
import { WebPushModule } from '../modules/web-push/index';
|
|
42
|
-
import { ChannelManager, type ChannelHandle } from '../modules/channel/index';
|
|
42
|
+
import { ChannelManager, type ChannelHandle, type ChannelState, type ChannelTransportFactory } from '../modules/channel/index';
|
|
43
43
|
import { surrealSignal, webrtcTransport } from '../modules/channel/webrtc';
|
|
44
|
+
import { roomLink, splitTransport } from '../modules/channel/room';
|
|
45
|
+
import { hubTransport } from '../modules/channel/hub';
|
|
44
46
|
import { DevToolsService } from '../modules/devtools/index';
|
|
45
47
|
import type { DevToolsQuerySource } from '../modules/devtools/index';
|
|
46
48
|
import { parseQueryParams, generateId } from '../utils/index';
|
|
@@ -187,6 +189,30 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
187
189
|
this.disposers.push(this.webPush.attach());
|
|
188
190
|
|
|
189
191
|
const channelsConfig = config.channels;
|
|
192
|
+
const relay = typeof channelsConfig?.relay === 'string' ? { url: channelsConfig.relay } : channelsConfig?.relay;
|
|
193
|
+
// Between users: a WebRTC link per pair of tabs, signaled through the database.
|
|
194
|
+
const mesh: ChannelTransportFactory = (hooks) =>
|
|
195
|
+
webrtcTransport(hooks, {
|
|
196
|
+
signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
|
|
197
|
+
iceServers: channelsConfig?.iceServers,
|
|
198
|
+
logger: s.logger,
|
|
199
|
+
});
|
|
200
|
+
// Between the user's own devices: one link per browser to their room on the relay.
|
|
201
|
+
const room: ChannelTransportFactory | null = relay
|
|
202
|
+
? (hooks) =>
|
|
203
|
+
hubTransport(hooks, {
|
|
204
|
+
scope: (user) => `${config.database.namespace}/${config.database.database}/${user}`,
|
|
205
|
+
link: (linkHooks) =>
|
|
206
|
+
roomLink(linkHooks, {
|
|
207
|
+
url: relay.url,
|
|
208
|
+
direct: relay.direct,
|
|
209
|
+
token: () => s.remote.getAuthToken(),
|
|
210
|
+
iceServers: channelsConfig?.iceServers,
|
|
211
|
+
logger: s.logger,
|
|
212
|
+
}),
|
|
213
|
+
logger: s.logger,
|
|
214
|
+
})
|
|
215
|
+
: null;
|
|
190
216
|
this.channels = new ChannelManager(config.schema, {
|
|
191
217
|
config: channelsConfig,
|
|
192
218
|
logger: s.logger,
|
|
@@ -195,15 +221,14 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
195
221
|
delete: (_table, id, ttlMs) => this.runtime.run(peerDelete(this.env, { recordId: id, ttlMs })),
|
|
196
222
|
read: (id) => this.runtime.run(readRow(id)),
|
|
197
223
|
},
|
|
198
|
-
transport:
|
|
199
|
-
channelsConfig?.transport ??
|
|
200
|
-
((hooks) =>
|
|
201
|
-
webrtcTransport(hooks, {
|
|
202
|
-
signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
|
|
203
|
-
iceServers: channelsConfig?.iceServers,
|
|
204
|
-
logger: s.logger,
|
|
205
|
-
})),
|
|
224
|
+
transport: channelsConfig?.transport ?? splitTransport(room, mesh),
|
|
206
225
|
});
|
|
226
|
+
if (this.channels.sharing && !relay && !channelsConfig?.transport) {
|
|
227
|
+
s.logger.warn(
|
|
228
|
+
{ Category: 'sp00ky-client::channel' },
|
|
229
|
+
'channels.share is set without channels.relay: nothing reaches your other devices until a relay address is given'
|
|
230
|
+
);
|
|
231
|
+
}
|
|
207
232
|
if (this.channels.enabled) this.disposers.push(s.auth.subscribe((userId) => this.channels.setUser(userId)));
|
|
208
233
|
|
|
209
234
|
const querySource: DevToolsQuerySource = {
|
|
@@ -442,7 +467,10 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
442
467
|
if (!this.channels.enabled) return this.runtime.subscribe(queryHash, callback, options);
|
|
443
468
|
// Channel values (peer updates, ephemeral fields) are folded into what
|
|
444
469
|
// subscribers see, never into the store.
|
|
445
|
-
|
|
470
|
+
// With `channels.share`, the user's other devices are told what this
|
|
471
|
+
// query can show, and only send what it has a use for.
|
|
472
|
+
const def = this.channels.sharing ? this.runtime.state.queries.get(queryHash)?.def : undefined;
|
|
473
|
+
const tap = this.channels.tap(callback, def ? this.channels.interestOf(def.plan, def.params) : null);
|
|
446
474
|
const stop = this.runtime.subscribe(queryHash, tap.feed, options);
|
|
447
475
|
return () => {
|
|
448
476
|
stop();
|
|
@@ -480,6 +508,21 @@ export class Sp00kyClient<S extends SchemaStructure> {
|
|
|
480
508
|
};
|
|
481
509
|
}
|
|
482
510
|
|
|
511
|
+
/**
|
|
512
|
+
* The link to this user's other devices (`channels.share`): `connected`
|
|
513
|
+
* with the user's id in `peers` while at least one other tab of theirs, in
|
|
514
|
+
* another browser, is in the room. `idle` when nothing is shared or nobody
|
|
515
|
+
* is signed in.
|
|
516
|
+
*/
|
|
517
|
+
shareState(): ChannelState {
|
|
518
|
+
return this.channels.ownState();
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Called at once with `shareState()`, then on every change. */
|
|
522
|
+
subscribeShareState(callback: (state: ChannelState) => void): () => void {
|
|
523
|
+
return this.channels.subscribeOwn(callback);
|
|
524
|
+
}
|
|
525
|
+
|
|
483
526
|
private channelScopes(queries: ChannelQuery<S, any> | ReadonlyArray<ChannelQuery<S, any>>) {
|
|
484
527
|
const list = (Array.isArray(queries) ? queries : [queries]) as ReadonlyArray<ChannelQuery<S, any>>;
|
|
485
528
|
return list.map((q) => {
|
package/src/index.ts
CHANGED
|
@@ -10,14 +10,21 @@ export {
|
|
|
10
10
|
unusedArgs,
|
|
11
11
|
type ChannelMessage,
|
|
12
12
|
type ChannelOp,
|
|
13
|
+
type ChannelRelayConfig,
|
|
14
|
+
type ChannelShareConfig,
|
|
15
|
+
type ChannelShareRule,
|
|
13
16
|
type ChannelState,
|
|
14
17
|
type ChannelStatus,
|
|
15
18
|
type ChannelTransport,
|
|
16
19
|
type ChannelTransportFactory,
|
|
20
|
+
type ChannelWire,
|
|
17
21
|
type ChannelsConfig,
|
|
22
|
+
type InterestMessage,
|
|
18
23
|
type PeerRef,
|
|
19
24
|
type TransportHooks,
|
|
20
25
|
} from './modules/channel/index';
|
|
26
|
+
export { roomLink, splitTransport, type RoomLink, type RoomLinkHooks, type RoomLinkOptions } from './modules/channel/room';
|
|
27
|
+
export { hubTransport, type HubOptions } from './modules/channel/hub';
|
|
21
28
|
export { webrtcTransport, surrealSignal, type SignalPort, type Signal, type OutgoingSignal } from './modules/channel/webrtc';
|
|
22
29
|
export {
|
|
23
30
|
FeatureFlagModule,
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import type { ChannelWire, TransportHooks } from './index';
|
|
3
|
+
import { hubTransport, type HubOptions } from './hub';
|
|
4
|
+
import { roomLink } from './room';
|
|
5
|
+
import { FakeRelay, fakeBrowser, memoryRoom, settle } from './rooms.fixture';
|
|
6
|
+
|
|
7
|
+
type Browser = ReturnType<typeof fakeBrowser>;
|
|
8
|
+
type Room = ReturnType<typeof memoryRoom>;
|
|
9
|
+
|
|
10
|
+
const USER = 'user:ann';
|
|
11
|
+
const op = (n: number): ChannelWire => ({ t: 'op', table: 'note', id: `note:${n}`, patch: { n }, hlc: [n, 0, 'x'] });
|
|
12
|
+
|
|
13
|
+
/** One tab of `USER` in `browser`: the transport and what it told the manager. */
|
|
14
|
+
function tab(browser: Browser, room: Room, peer: string, extra: Partial<HubOptions> = {}) {
|
|
15
|
+
const events: string[] = [];
|
|
16
|
+
const messages: Array<[string, unknown]> = [];
|
|
17
|
+
const status: string[] = [];
|
|
18
|
+
let signedIn = true;
|
|
19
|
+
const hooks: TransportHooks = {
|
|
20
|
+
self: () => (signedIn ? { user: USER, peer } : null),
|
|
21
|
+
onMessage: (from, m) => messages.push([from.peer, m]),
|
|
22
|
+
onPeer: (p, up) => events.push(`${up ? 'up' : 'down'} ${p.peer}`),
|
|
23
|
+
onStatus: (_user, s) => status.push(s),
|
|
24
|
+
};
|
|
25
|
+
const t = hubTransport(hooks, { scope: (user) => `ns/db/${user}`, link: room.link, locks: browser.locks, bus: browser.bus, supported: true, ...extra });
|
|
26
|
+
return {
|
|
27
|
+
t,
|
|
28
|
+
events,
|
|
29
|
+
messages,
|
|
30
|
+
status,
|
|
31
|
+
peer,
|
|
32
|
+
join: () => t.want(new Set([USER])),
|
|
33
|
+
to: (...peers: string[]) => peers.map((p) => ({ user: USER, peer: p })),
|
|
34
|
+
signOut: () => (signedIn = false),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Two browsers, two tabs each, all in the room. */
|
|
39
|
+
async function twoByTwo() {
|
|
40
|
+
const room = memoryRoom();
|
|
41
|
+
const left = fakeBrowser();
|
|
42
|
+
const right = fakeBrowser();
|
|
43
|
+
const a1 = tab(left, room, 'a1');
|
|
44
|
+
const a2 = tab(left, room, 'a2');
|
|
45
|
+
const b1 = tab(right, room, 'b1');
|
|
46
|
+
const b2 = tab(right, room, 'b2');
|
|
47
|
+
for (const t of [a1, a2, b1, b2]) t.join();
|
|
48
|
+
await settle();
|
|
49
|
+
return { room, left, right, a1, a2, b1, b2 };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
describe('hubTransport', () => {
|
|
53
|
+
it('keeps one link per browser, and shows every tab the tabs of the other browsers', async () => {
|
|
54
|
+
const { room, a1, a2, b1, b2 } = await twoByTwo();
|
|
55
|
+
expect([...room.members.keys()].sort()).toEqual(['a1', 'b1']);
|
|
56
|
+
for (const t of [a1, a2]) expect([...t.events].sort()).toEqual(['up b1', 'up b2']);
|
|
57
|
+
for (const t of [b1, b2]) expect([...t.events].sort()).toEqual(['up a1', 'up a2']);
|
|
58
|
+
for (const t of [a1, a2, b1, b2]) expect(t.status.at(-1)).toBe('connected');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('carries a message from any tab to the tabs it names, as one frame', async () => {
|
|
62
|
+
const { room, a1, a2, b1, b2 } = await twoByTwo();
|
|
63
|
+
const before = room.frames.length;
|
|
64
|
+
// The manager sends one message to each peer in turn.
|
|
65
|
+
const m = op(1);
|
|
66
|
+
for (const to of a2.to('b1', 'b2')) a2.t.send(to, m);
|
|
67
|
+
await settle();
|
|
68
|
+
expect(b1.messages).toEqual([['a2', m]]);
|
|
69
|
+
expect(b2.messages).toEqual([['a2', m]]);
|
|
70
|
+
expect(a1.messages).toEqual([]);
|
|
71
|
+
expect(room.frames.length - before).toBe(1);
|
|
72
|
+
|
|
73
|
+
b1.t.send(b1.to('a2')[0], op(2));
|
|
74
|
+
await settle();
|
|
75
|
+
expect(a2.messages).toEqual([['b1', op(2)]]);
|
|
76
|
+
expect(a1.messages).toEqual([]);
|
|
77
|
+
|
|
78
|
+
// Another user, or a tab nobody speaks for: nowhere to go.
|
|
79
|
+
a1.t.send({ user: 'user:bob', peer: 'b1' }, op(3));
|
|
80
|
+
a1.t.send({ user: USER, peer: 'ghost' }, op(4));
|
|
81
|
+
await settle();
|
|
82
|
+
expect(b1.messages).toHaveLength(1);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('hands the link to the next tab when the one holding it closes', async () => {
|
|
86
|
+
const { room, a1, a2, b1, b2 } = await twoByTwo();
|
|
87
|
+
a1.t.close();
|
|
88
|
+
await settle();
|
|
89
|
+
expect([...room.members.keys()].sort()).toEqual(['a2', 'b1']);
|
|
90
|
+
// The other browser saw the old link go and the remaining tab return.
|
|
91
|
+
expect(b1.events.slice(2).sort()).toEqual(['down a1', 'down a2', 'up a2']);
|
|
92
|
+
expect(b2.events.slice(2).sort()).toEqual(['down a1', 'down a2', 'up a2']);
|
|
93
|
+
expect(a2.events.filter((e) => e.startsWith('up')).length).toBe(4);
|
|
94
|
+
a2.t.send(a2.to('b2')[0], op(5));
|
|
95
|
+
b1.t.send(b1.to('a2')[0], op(6));
|
|
96
|
+
await settle();
|
|
97
|
+
expect(b2.messages).toEqual([['a2', op(5)]]);
|
|
98
|
+
expect(a2.messages).toEqual([['b1', op(6)]]);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('tells the other browsers when a tab is gone, however it went', async () => {
|
|
102
|
+
const { a1, a2, b1, b2 } = await twoByTwo();
|
|
103
|
+
a2.t.close();
|
|
104
|
+
await settle();
|
|
105
|
+
expect(b1.events.at(-1)).toBe('down a2');
|
|
106
|
+
expect(b2.events.at(-1)).toBe('down a2');
|
|
107
|
+
expect(a1.events).toHaveLength(2);
|
|
108
|
+
|
|
109
|
+
// A tab that crashes says no goodbye: its lock going free is what tells.
|
|
110
|
+
const { room, left, right } = { room: memoryRoom(), left: fakeBrowser(), right: fakeBrowser() };
|
|
111
|
+
const c1 = tab(left, room, 'c1');
|
|
112
|
+
const c2 = tab(left, room, 'c2');
|
|
113
|
+
const d1 = tab(right, room, 'd1');
|
|
114
|
+
for (const t of [c1, c2, d1]) t.join();
|
|
115
|
+
await settle();
|
|
116
|
+
expect([...d1.events].sort()).toEqual(['up c1', 'up c2']);
|
|
117
|
+
for (const b of left.opened) (b as unknown as { silent: boolean }).silent = true;
|
|
118
|
+
c2.t.close();
|
|
119
|
+
for (const b of left.opened) (b as unknown as { silent: boolean }).silent = false;
|
|
120
|
+
await settle();
|
|
121
|
+
expect(d1.events.at(-1)).toBe('down c2');
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('brings a tab opened later up to date', async () => {
|
|
125
|
+
const { room, left, a1, b1 } = await twoByTwo();
|
|
126
|
+
const a3 = tab(left, room, 'a3');
|
|
127
|
+
a3.join();
|
|
128
|
+
await settle();
|
|
129
|
+
expect([...a3.events].sort()).toEqual(['up b1', 'up b2']);
|
|
130
|
+
expect(a3.status.at(-1)).toBe('connected');
|
|
131
|
+
expect(b1.events.at(-1)).toBe('up a3');
|
|
132
|
+
expect(a1.events).toHaveLength(2);
|
|
133
|
+
expect(room.members.size).toBe(2);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('leaves when the user is no longer wanted, and returns when wanted again', async () => {
|
|
137
|
+
const { room, a1, a2, b1 } = await twoByTwo();
|
|
138
|
+
a1.t.want(new Set());
|
|
139
|
+
await settle();
|
|
140
|
+
expect(a1.events.slice(2).sort()).toEqual(['down b1', 'down b2']);
|
|
141
|
+
expect([...room.members.keys()].sort()).toEqual(['a2', 'b1']);
|
|
142
|
+
a1.t.want(new Set([USER]));
|
|
143
|
+
await settle();
|
|
144
|
+
expect(a1.events.slice(4).sort()).toEqual(['up b1', 'up b2']);
|
|
145
|
+
expect(b1.events.at(-1)).toBe('up a1');
|
|
146
|
+
// Signed out: nothing to join as.
|
|
147
|
+
a2.signOut();
|
|
148
|
+
a2.t.want(new Set([USER]));
|
|
149
|
+
await settle();
|
|
150
|
+
expect(room.members.has('a2')).toBe(false);
|
|
151
|
+
a2.t.send(a2.to('b1')[0], op(7));
|
|
152
|
+
await settle();
|
|
153
|
+
expect(b1.messages).toEqual([]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('gives every tab a link of its own without Web Locks or a BroadcastChannel', async () => {
|
|
157
|
+
const room = memoryRoom();
|
|
158
|
+
const browser = fakeBrowser();
|
|
159
|
+
const a1 = tab(browser, room, 'a1', { locks: null });
|
|
160
|
+
const a2 = tab(browser, room, 'a2', { bus: null });
|
|
161
|
+
a1.join();
|
|
162
|
+
a2.join();
|
|
163
|
+
await settle();
|
|
164
|
+
expect([...room.members.keys()].sort()).toEqual(['a1', 'a2']);
|
|
165
|
+
expect(a1.events).toEqual(['up a2']);
|
|
166
|
+
a1.t.send(a1.to('a2')[0], op(8));
|
|
167
|
+
await settle();
|
|
168
|
+
expect(a2.messages).toEqual([['a1', op(8)]]);
|
|
169
|
+
a1.t.close();
|
|
170
|
+
await settle();
|
|
171
|
+
expect(a2.events).toEqual(['up a1', 'down a1']);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('knows the other browser\'s tabs again after its socket was replaced', async () => {
|
|
175
|
+
// Over the real link and a relay: a socket that died where only the
|
|
176
|
+
// client could tell comes back under the same id.
|
|
177
|
+
const relay = new FakeRelay();
|
|
178
|
+
const viaRelay = (hooks: Parameters<typeof roomLink>[0]) =>
|
|
179
|
+
roomLink(hooks, { url: 'ws://relay.test/room', token: () => 't-ann', WebSocket: relay.WebSocket, direct: false });
|
|
180
|
+
const room = { link: viaRelay } as unknown as Room;
|
|
181
|
+
const a1 = tab(fakeBrowser(), room, 'a1');
|
|
182
|
+
const right = fakeBrowser();
|
|
183
|
+
const b1 = tab(right, room, 'b1');
|
|
184
|
+
const b2 = tab(right, room, 'b2');
|
|
185
|
+
for (const t of [a1, b1, b2]) t.join();
|
|
186
|
+
await settle();
|
|
187
|
+
expect([...a1.events].sort()).toEqual(['up b1', 'up b2']);
|
|
188
|
+
|
|
189
|
+
relay.sockets[0].sever();
|
|
190
|
+
await new Promise((r) => setTimeout(r, 900));
|
|
191
|
+
await settle();
|
|
192
|
+
expect(a1.status.at(-1)).toBe('connected');
|
|
193
|
+
// Down with the socket, and up again once the other hub said its tabs anew.
|
|
194
|
+
expect(a1.events.slice(2).sort()).toEqual(['down b1', 'down b2', 'up b1', 'up b2']);
|
|
195
|
+
expect(b1.events).toEqual(['up a1', 'down a1', 'up a1']);
|
|
196
|
+
a1.t.send(a1.to('b2')[0], op(11));
|
|
197
|
+
b1.t.send(b1.to('a1')[0], op(12));
|
|
198
|
+
await settle();
|
|
199
|
+
expect(b2.messages).toEqual([['a1', op(11)]]);
|
|
200
|
+
expect(a1.messages).toEqual([['b1', op(12)]]);
|
|
201
|
+
for (const t of [a1, b1, b2]) t.t.close();
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('takes a message only from a tab its browser speaks for', async () => {
|
|
205
|
+
const { room, b1, b2 } = await twoByTwo();
|
|
206
|
+
const a1Link = room.members.get('a1');
|
|
207
|
+
const forge = (data: unknown) => room.members.get('b1')?.onMessage('a1', data);
|
|
208
|
+
forge({ h: 'm', from: 'zz', to: null, m: op(9) });
|
|
209
|
+
forge({ h: 'm', from: 'a1', to: 'b1', m: op(9) });
|
|
210
|
+
forge({ h: 'tabs', tabs: 'nope' });
|
|
211
|
+
forge({ h: 'what' });
|
|
212
|
+
forge(null);
|
|
213
|
+
room.members.get('b1')?.onMessage('stranger', { h: 'm', from: 'a1', to: null, m: op(9) });
|
|
214
|
+
await settle();
|
|
215
|
+
expect(b1.messages).toEqual([]);
|
|
216
|
+
expect(b2.messages).toEqual([]);
|
|
217
|
+
forge({ h: 'm', from: 'a1', to: null, m: op(10) });
|
|
218
|
+
await settle();
|
|
219
|
+
expect(b1.messages).toEqual([['a1', op(10)]]);
|
|
220
|
+
expect(b2.messages).toEqual([['a1', op(10)]]);
|
|
221
|
+
expect(a1Link).toBeDefined();
|
|
222
|
+
});
|
|
223
|
+
});
|