@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.11
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 +4 -3
- package/dist/index.d.ts +170 -9
- package/dist/index.js +5398 -2968
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2731 -0
- package/dist/sqlite-open.js +1 -1
- package/dist/sqlite-worker.js +1 -1
- package/dist/types.d.ts +131 -13
- package/package.json +9 -4
- package/scripts/check-worker-entries.mjs +15 -2
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/bucket-handle.ts +21 -1
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/services.ts +4 -1
- package/src/client/sp00ky-client.test.ts +143 -1
- package/src/client/sp00ky-client.ts +158 -19
- package/src/index.ts +9 -0
- package/src/kernel/effects.ts +12 -2
- package/src/kernel/interpreter.test.ts +17 -0
- package/src/kernel/interpreter.ts +5 -2
- 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/modules/devtools/storage-info.ts +4 -3
- package/src/query/materialize.saga.test.ts +16 -0
- package/src/query/materialize.saga.ts +7 -26
- package/src/query/materialize.ts +79 -3
- package/src/query/register.saga.test.ts +61 -0
- package/src/query/register.saga.ts +39 -2
- package/src/services/database/cache-engine.ts +17 -3
- package/src/services/database/engine-factory.ts +7 -0
- package/src/services/database/index.ts +1 -0
- package/src/services/database/rows-cache-engine.test.ts +1584 -0
- package/src/services/database/rows-cache-engine.ts +1203 -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 +251 -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 +607 -0
- package/src/services/database/rows-yield.test.ts +141 -0
- package/src/services/database/rows-yield.ts +92 -0
- package/src/services/database/sqlite-cache-engine.test.ts +22 -1
- package/src/services/database/sqlite-cache-engine.ts +55 -34
- package/src/services/database/sqlite-transport.ts +7 -5
- package/src/services/tabs/support.ts +6 -4
- package/src/types.ts +41 -6
- package/tsdown.config.ts +42 -1
- package/vitest.config.ts +4 -0
|
@@ -108,12 +108,41 @@ export interface ChannelTransport {
|
|
|
108
108
|
readonly supported: boolean;
|
|
109
109
|
/** Users this tab wants connections to: the union over open channels. */
|
|
110
110
|
want(users: ReadonlySet<string>): void;
|
|
111
|
-
send(to: PeerRef, message:
|
|
111
|
+
send(to: PeerRef, message: ChannelWire): void;
|
|
112
112
|
close(): void;
|
|
113
113
|
}
|
|
114
114
|
|
|
115
115
|
export type ChannelTransportFactory = (hooks: TransportHooks) => ChannelTransport;
|
|
116
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
|
+
|
|
117
146
|
export interface ChannelsConfig {
|
|
118
147
|
/**
|
|
119
148
|
* Per table: decide whether to apply a peer's update. Runs after the
|
|
@@ -128,6 +157,18 @@ export interface ChannelsConfig {
|
|
|
128
157
|
transport?: ChannelTransportFactory;
|
|
129
158
|
/** How long a peer's persistent value shows without the server confirming it. Default 5000. */
|
|
130
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;
|
|
131
172
|
}
|
|
132
173
|
|
|
133
174
|
// ---- pure helpers ----------------------------------------------------------------
|
|
@@ -363,6 +404,8 @@ export function peerUsers(peers: Iterable<unknown>, self: string | null): Set<st
|
|
|
363
404
|
export interface ChannelScope {
|
|
364
405
|
readonly table: string;
|
|
365
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;
|
|
366
409
|
}
|
|
367
410
|
|
|
368
411
|
const OPS: Record<string, (a: unknown, b: unknown) => boolean> = {
|
|
@@ -481,6 +524,190 @@ export function compileScope(schema: SchemaStructure, plan: QueryPlan): ChannelS
|
|
|
481
524
|
return { table: plan.table, where };
|
|
482
525
|
}
|
|
483
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
|
+
|
|
484
711
|
// ---- manager ---------------------------------------------------------------------
|
|
485
712
|
|
|
486
713
|
interface Tap {
|
|
@@ -488,6 +715,8 @@ interface Tap {
|
|
|
488
715
|
raw: Row[] | null;
|
|
489
716
|
/** Every record id in `raw`, computed on first need. */
|
|
490
717
|
ids: Set<string> | null;
|
|
718
|
+
/** What its query can show, or null when nobody said. */
|
|
719
|
+
readonly interest: ReadonlyArray<QueryInterest> | null;
|
|
491
720
|
}
|
|
492
721
|
|
|
493
722
|
interface Channel {
|
|
@@ -498,6 +727,8 @@ interface Channel {
|
|
|
498
727
|
readonly listeners: Set<(s: ChannelState) => void>;
|
|
499
728
|
state: ChannelState;
|
|
500
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;
|
|
501
732
|
}
|
|
502
733
|
|
|
503
734
|
/** An open channel. `client.channel(...)` wraps it with scoped writes. */
|
|
@@ -554,6 +785,14 @@ export class ChannelManager {
|
|
|
554
785
|
/** Unused-argument warnings already given, so a reactive query does not repeat them. */
|
|
555
786
|
private readonly warnedUnused = new Set<string>();
|
|
556
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;
|
|
557
796
|
private user: string | null = null;
|
|
558
797
|
private clock: Hlc;
|
|
559
798
|
private transport: ChannelTransport | null = null;
|
|
@@ -567,18 +806,64 @@ export class ChannelManager {
|
|
|
567
806
|
private readonly deps: ChannelManagerDeps = {}
|
|
568
807
|
) {
|
|
569
808
|
this.schema = schema;
|
|
570
|
-
|
|
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) }]));
|
|
571
820
|
this.now = deps.now ?? Date.now;
|
|
572
821
|
this.confirmMs = Math.max(0, deps.config?.confirmTimeoutMs ?? 5000);
|
|
573
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
|
+
}
|
|
574
835
|
}
|
|
575
836
|
|
|
576
|
-
/** True when any table is a channel table; otherwise the client skips all of this. */
|
|
837
|
+
/** True when any table is a channel table or shared; otherwise the client skips all of this. */
|
|
577
838
|
get enabled(): boolean {
|
|
578
839
|
for (const t of this.tables.values()) if (t.channel) return true;
|
|
579
840
|
return false;
|
|
580
841
|
}
|
|
581
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
|
+
|
|
582
867
|
/** The signed-in user changed: peers, their values and the transport start over. */
|
|
583
868
|
setUser(user: string | null): void {
|
|
584
869
|
if (user === this.user) return;
|
|
@@ -587,9 +872,11 @@ export class ChannelManager {
|
|
|
587
872
|
this.transport = null;
|
|
588
873
|
this.connected.clear();
|
|
589
874
|
this.userStatus.clear();
|
|
875
|
+
this.interest.clear();
|
|
876
|
+
this.announced = null;
|
|
590
877
|
const touched = new Set(this.overlay.keys());
|
|
591
878
|
this.overlay.clear();
|
|
592
|
-
for (const ch of this.channels) ch.users = peerUsers(ch.listed, user);
|
|
879
|
+
for (const ch of this.channels) ch.users = ch.own ? new Set(user ? [user] : []) : peerUsers(ch.listed, user);
|
|
593
880
|
this.syncWanted();
|
|
594
881
|
this.emitFor(touched);
|
|
595
882
|
this.notifyAll();
|
|
@@ -675,9 +962,10 @@ export class ChannelManager {
|
|
|
675
962
|
* Follow a subscription: `feed` it the raw rows, and `cb` gets them with
|
|
676
963
|
* the overlay folded in, again whenever the overlay changes for its rows.
|
|
677
964
|
*/
|
|
678
|
-
tap(cb: (rows: Row[]) => void): { feed: (rows: Row[]) => void; stop: () => void } {
|
|
679
|
-
const tap: Tap = { cb, raw: null, ids: null };
|
|
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 };
|
|
680
967
|
this.taps.add(tap);
|
|
968
|
+
this.announceSoon();
|
|
681
969
|
return {
|
|
682
970
|
feed: (rows) => {
|
|
683
971
|
tap.raw = rows;
|
|
@@ -685,7 +973,7 @@ export class ChannelManager {
|
|
|
685
973
|
this.emit(tap);
|
|
686
974
|
},
|
|
687
975
|
stop: () => {
|
|
688
|
-
this.taps.delete(tap);
|
|
976
|
+
if (this.taps.delete(tap)) this.announceSoon();
|
|
689
977
|
},
|
|
690
978
|
};
|
|
691
979
|
}
|
|
@@ -729,7 +1017,8 @@ export class ChannelManager {
|
|
|
729
1017
|
// out of a channel's filter still reaches its peers.
|
|
730
1018
|
void this.rowFor(rid).then((row) => {
|
|
731
1019
|
const after = { ...(row ?? { id: rid }), ...patch };
|
|
732
|
-
|
|
1020
|
+
const rows = row ? [row, after] : [after];
|
|
1021
|
+
this.send(this.targets(table, rows, scope), table, rid, patch, hlc, 'update', rows);
|
|
733
1022
|
});
|
|
734
1023
|
}
|
|
735
1024
|
|
|
@@ -750,7 +1039,8 @@ export class ChannelManager {
|
|
|
750
1039
|
this.overlay.set(rid, map);
|
|
751
1040
|
this.emitFor(new Set([rid]));
|
|
752
1041
|
}
|
|
753
|
-
|
|
1042
|
+
const rows = [{ ...full, id: rid }];
|
|
1043
|
+
this.send(this.targets(table, rows, scope), table, rid, full, hlc, 'create', rows);
|
|
754
1044
|
}
|
|
755
1045
|
|
|
756
1046
|
/**
|
|
@@ -763,13 +1053,14 @@ export class ChannelManager {
|
|
|
763
1053
|
const rid = normalizeId(table, id);
|
|
764
1054
|
const hlc = this.tick();
|
|
765
1055
|
const row = await this.rowFor(rid);
|
|
766
|
-
if (row) this.send(this.targets(table, [row], scope), table, rid, {}, hlc, 'delete');
|
|
1056
|
+
if (row) this.send(this.targets(table, [row], scope), table, rid, {}, hlc, 'delete', [row]);
|
|
767
1057
|
if (this.overlay.delete(rid)) this.emitFor(new Set([rid]));
|
|
768
1058
|
}
|
|
769
1059
|
|
|
770
1060
|
/** A transport delivered a message from `from`. */
|
|
771
1061
|
receive(from: PeerRef, raw: unknown): void {
|
|
772
1062
|
if (this.closed) return;
|
|
1063
|
+
if (raw !== null && typeof raw === 'object' && (raw as { t?: unknown }).t === 'interest') return this.receiveInterest(from, raw);
|
|
773
1064
|
const msg = parseMessage(raw);
|
|
774
1065
|
if (!msg) return this.drop(from, 'malformed message');
|
|
775
1066
|
this.observe(msg.hlc);
|
|
@@ -861,6 +1152,14 @@ export class ChannelManager {
|
|
|
861
1152
|
);
|
|
862
1153
|
}
|
|
863
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
|
+
|
|
864
1163
|
private accepts(op: ChannelOp): boolean {
|
|
865
1164
|
const rule = this.deps.config?.accept?.[op.table];
|
|
866
1165
|
if (!rule) return true;
|
|
@@ -878,9 +1177,11 @@ export class ChannelManager {
|
|
|
878
1177
|
if (up) {
|
|
879
1178
|
this.connected.set(key, peer);
|
|
880
1179
|
this.userStatus.set(peer.user, 'connected');
|
|
1180
|
+
if (this.ownChannel && peer.user === this.user) this.transport?.send(peer, encodeInterest(this.ownInterest()));
|
|
881
1181
|
this.sendSnapshot(peer);
|
|
882
1182
|
} else {
|
|
883
1183
|
this.connected.delete(key);
|
|
1184
|
+
this.interest.delete(key);
|
|
884
1185
|
const touched = new Set<string>();
|
|
885
1186
|
for (const [rid, fields] of this.overlay) {
|
|
886
1187
|
for (const [f, e] of fields) {
|
|
@@ -952,7 +1253,8 @@ export class ChannelManager {
|
|
|
952
1253
|
private targets(table: string, rows: ReadonlyArray<Row>, scope?: ChannelHandle): ReadonlySet<string> {
|
|
953
1254
|
const users = new Set<string>();
|
|
954
1255
|
const pick = scope ? this.handles.get(scope) : undefined;
|
|
955
|
-
|
|
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) {
|
|
956
1258
|
if (ch.closed || !carries(ch, table, rows)) continue;
|
|
957
1259
|
for (const u of ch.users) users.add(u);
|
|
958
1260
|
}
|
|
@@ -967,14 +1269,45 @@ export class ChannelManager {
|
|
|
967
1269
|
return stored ? applyOverlay([stored], this.overlay)[0] : null;
|
|
968
1270
|
}
|
|
969
1271
|
|
|
970
|
-
private send(users: ReadonlySet<string>, table: string, rid: string, patch: Row, hlc: Hlc, kind: ChannelOpKind): void {
|
|
1272
|
+
private send(users: ReadonlySet<string>, table: string, rid: string, patch: Row, hlc: Hlc, kind: ChannelOpKind, rows: ReadonlyArray<Row>): void {
|
|
971
1273
|
const transport = this.transport;
|
|
972
1274
|
if (!transport || users.size === 0) return;
|
|
973
1275
|
const encoded: Row = {};
|
|
974
1276
|
for (const [k, v] of Object.entries(patch)) encoded[k] = encodeValue(v);
|
|
975
1277
|
const message: ChannelMessage =
|
|
976
1278
|
kind === 'update' ? { t: 'op', table, id: rid, patch: encoded, hlc } : { t: 'op', kind, table, id: rid, patch: encoded, hlc };
|
|
977
|
-
for (const peer of this.connected
|
|
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
|
+
});
|
|
978
1311
|
}
|
|
979
1312
|
|
|
980
1313
|
/** Own ephemeral values of rows inside a channel a newly connected peer is listed on. */
|
|
@@ -1109,9 +1442,20 @@ export class ChannelManager {
|
|
|
1109
1442
|
|
|
1110
1443
|
/** Whether a channel has a query on `table` that one of `rows` matches. */
|
|
1111
1444
|
function carries(ch: Channel, table: string, rows: ReadonlyArray<Row>): boolean {
|
|
1112
|
-
return ch.scopes.some((sc) => sc.table === table && rows.some((r) => matchesWhere(sc.where, r)));
|
|
1445
|
+
return ch.scopes.some((sc) => sc.table === table && rows.some((r) => matchesWhere(sc.where, r) && (!sc.test || sc.test(r))));
|
|
1113
1446
|
}
|
|
1114
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
|
+
|
|
1115
1459
|
/** The fields of `row` the table has as plain columns (no id, no `@crdt`). */
|
|
1116
1460
|
function pickColumns(columns: Record<string, ColumnSchema>, row: Row): Row {
|
|
1117
1461
|
const out: Row = {};
|