nowity 1.0.0

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.
Files changed (192) hide show
  1. package/README.md +751 -0
  2. package/dist/api/contract.d.ts +186 -0
  3. package/dist/api/contract.d.ts.map +1 -0
  4. package/dist/api/contract.js +251 -0
  5. package/dist/api/errors.d.ts +50 -0
  6. package/dist/api/errors.d.ts.map +1 -0
  7. package/dist/api/errors.js +50 -0
  8. package/dist/api/index.d.ts +13 -0
  9. package/dist/api/index.d.ts.map +1 -0
  10. package/dist/api/index.js +32 -0
  11. package/dist/client/confirmed-store.d.ts +33 -0
  12. package/dist/client/confirmed-store.d.ts.map +1 -0
  13. package/dist/client/confirmed-store.js +123 -0
  14. package/dist/client/connection.d.ts +102 -0
  15. package/dist/client/connection.d.ts.map +1 -0
  16. package/dist/client/connection.js +285 -0
  17. package/dist/client/list.d.ts +102 -0
  18. package/dist/client/list.d.ts.map +1 -0
  19. package/dist/client/list.js +257 -0
  20. package/dist/client/live-query.d.ts +153 -0
  21. package/dist/client/live-query.d.ts.map +1 -0
  22. package/dist/client/live-query.js +244 -0
  23. package/dist/client/nowity-client.d.ts +188 -0
  24. package/dist/client/nowity-client.d.ts.map +1 -0
  25. package/dist/client/nowity-client.js +580 -0
  26. package/dist/client/null-transport.d.ts +16 -0
  27. package/dist/client/null-transport.d.ts.map +1 -0
  28. package/dist/client/null-transport.js +17 -0
  29. package/dist/client/overlay.d.ts +44 -0
  30. package/dist/client/overlay.d.ts.map +1 -0
  31. package/dist/client/overlay.js +90 -0
  32. package/dist/client/query-source.d.ts +78 -0
  33. package/dist/client/query-source.d.ts.map +1 -0
  34. package/dist/client/query-source.js +57 -0
  35. package/dist/client/ssr-source.d.ts +70 -0
  36. package/dist/client/ssr-source.d.ts.map +1 -0
  37. package/dist/client/ssr-source.js +134 -0
  38. package/dist/client/transport.d.ts +19 -0
  39. package/dist/client/transport.d.ts.map +1 -0
  40. package/dist/client/transport.js +2 -0
  41. package/dist/client/ws-transport.d.ts +30 -0
  42. package/dist/client/ws-transport.d.ts.map +1 -0
  43. package/dist/client/ws-transport.js +89 -0
  44. package/dist/client.d.ts +47 -0
  45. package/dist/client.d.ts.map +1 -0
  46. package/dist/client.js +80 -0
  47. package/dist/core/diff.d.ts +14 -0
  48. package/dist/core/diff.d.ts.map +1 -0
  49. package/dist/core/diff.js +56 -0
  50. package/dist/core/normalize.d.ts +16 -0
  51. package/dist/core/normalize.d.ts.map +1 -0
  52. package/dist/core/normalize.js +67 -0
  53. package/dist/core/protocol.d.ts +215 -0
  54. package/dist/core/protocol.d.ts.map +1 -0
  55. package/dist/core/protocol.js +14 -0
  56. package/dist/core/ssr-bridge.d.ts +69 -0
  57. package/dist/core/ssr-bridge.d.ts.map +1 -0
  58. package/dist/core/ssr-bridge.js +40 -0
  59. package/dist/core/types.d.ts +96 -0
  60. package/dist/core/types.d.ts.map +1 -0
  61. package/dist/core/types.js +17 -0
  62. package/dist/index.d.ts +47 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +98 -0
  65. package/dist/ironbean/client.d.ts +7 -0
  66. package/dist/ironbean/client.d.ts.map +1 -0
  67. package/dist/ironbean/client.js +38 -0
  68. package/dist/ironbean/server.d.ts +42 -0
  69. package/dist/ironbean/server.d.ts.map +1 -0
  70. package/dist/ironbean/server.js +62 -0
  71. package/dist/ironbean/tokens.d.ts +26 -0
  72. package/dist/ironbean/tokens.d.ts.map +1 -0
  73. package/dist/ironbean/tokens.js +23 -0
  74. package/dist/next/config.d.ts +7 -0
  75. package/dist/next/config.d.ts.map +1 -0
  76. package/dist/next/config.js +77 -0
  77. package/dist/next/live.d.ts +69 -0
  78. package/dist/next/live.d.ts.map +1 -0
  79. package/dist/next/live.js +70 -0
  80. package/dist/next/serve.d.ts +44 -0
  81. package/dist/next/serve.d.ts.map +1 -0
  82. package/dist/next/serve.js +107 -0
  83. package/dist/next/server.d.ts +62 -0
  84. package/dist/next/server.d.ts.map +1 -0
  85. package/dist/next/server.js +127 -0
  86. package/dist/react/connection-context.d.ts +4 -0
  87. package/dist/react/connection-context.d.ts.map +1 -0
  88. package/dist/react/connection-context.js +28 -0
  89. package/dist/react/grid-list.d.ts +34 -0
  90. package/dist/react/grid-list.d.ts.map +1 -0
  91. package/dist/react/grid-list.js +62 -0
  92. package/dist/react/hydrate.d.ts +22 -0
  93. package/dist/react/hydrate.d.ts.map +1 -0
  94. package/dist/react/hydrate.js +18 -0
  95. package/dist/react/index.d.ts +35 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +51 -0
  98. package/dist/react/list.d.ts +31 -0
  99. package/dist/react/list.d.ts.map +1 -0
  100. package/dist/react/list.js +35 -0
  101. package/dist/react/prerendered.d.ts +33 -0
  102. package/dist/react/prerendered.d.ts.map +1 -0
  103. package/dist/react/prerendered.js +165 -0
  104. package/dist/react/provider.d.ts +64 -0
  105. package/dist/react/provider.d.ts.map +1 -0
  106. package/dist/react/provider.js +130 -0
  107. package/dist/react/refusals.d.ts +31 -0
  108. package/dist/react/refusals.d.ts.map +1 -0
  109. package/dist/react/refusals.js +51 -0
  110. package/dist/react/restricted.d.ts +76 -0
  111. package/dist/react/restricted.d.ts.map +1 -0
  112. package/dist/react/restricted.js +126 -0
  113. package/dist/react/use-list.d.ts +42 -0
  114. package/dist/react/use-list.d.ts.map +1 -0
  115. package/dist/react/use-list.js +56 -0
  116. package/dist/react/use-query.d.ts +66 -0
  117. package/dist/react/use-query.d.ts.map +1 -0
  118. package/dist/react/use-query.js +126 -0
  119. package/dist/react/virtual.d.ts +60 -0
  120. package/dist/react/virtual.d.ts.map +1 -0
  121. package/dist/react/virtual.js +131 -0
  122. package/dist/server/api/auth.d.ts +37 -0
  123. package/dist/server/api/auth.d.ts.map +1 -0
  124. package/dist/server/api/auth.js +54 -0
  125. package/dist/server/api/bridge.d.ts +28 -0
  126. package/dist/server/api/bridge.d.ts.map +1 -0
  127. package/dist/server/api/bridge.js +330 -0
  128. package/dist/server/api/collector.d.ts +25 -0
  129. package/dist/server/api/collector.d.ts.map +1 -0
  130. package/dist/server/api/collector.js +184 -0
  131. package/dist/server/api/configure.d.ts +31 -0
  132. package/dist/server/api/configure.d.ts.map +1 -0
  133. package/dist/server/api/configure.js +67 -0
  134. package/dist/server/api/execution.d.ts +77 -0
  135. package/dist/server/api/execution.d.ts.map +1 -0
  136. package/dist/server/api/execution.js +97 -0
  137. package/dist/server/api/list.d.ts +141 -0
  138. package/dist/server/api/list.d.ts.map +1 -0
  139. package/dist/server/api/list.js +281 -0
  140. package/dist/server/api/prerender.d.ts +32 -0
  141. package/dist/server/api/prerender.d.ts.map +1 -0
  142. package/dist/server/api/prerender.js +69 -0
  143. package/dist/server/api/read-keys.d.ts +128 -0
  144. package/dist/server/api/read-keys.d.ts.map +1 -0
  145. package/dist/server/api/read-keys.js +464 -0
  146. package/dist/server/api/read-set.d.ts +103 -0
  147. package/dist/server/api/read-set.d.ts.map +1 -0
  148. package/dist/server/api/read-set.js +210 -0
  149. package/dist/server/api/runtime.d.ts +36 -0
  150. package/dist/server/api/runtime.d.ts.map +1 -0
  151. package/dist/server/api/runtime.js +49 -0
  152. package/dist/server/api/tracked-client.d.ts +6 -0
  153. package/dist/server/api/tracked-client.d.ts.map +1 -0
  154. package/dist/server/api/tracked-client.js +56 -0
  155. package/dist/server/change-source/change-source.d.ts +41 -0
  156. package/dist/server/change-source/change-source.d.ts.map +1 -0
  157. package/dist/server/change-source/change-source.js +2 -0
  158. package/dist/server/change-source/outbox-change-source.d.ts +106 -0
  159. package/dist/server/change-source/outbox-change-source.d.ts.map +1 -0
  160. package/dist/server/change-source/outbox-change-source.js +237 -0
  161. package/dist/server/change-source/wal-change-source.d.ts +85 -0
  162. package/dist/server/change-source/wal-change-source.d.ts.map +1 -0
  163. package/dist/server/change-source/wal-change-source.js +193 -0
  164. package/dist/server/db.d.ts +51 -0
  165. package/dist/server/db.d.ts.map +1 -0
  166. package/dist/server/db.js +53 -0
  167. package/dist/server/evaluate.d.ts +39 -0
  168. package/dist/server/evaluate.d.ts.map +1 -0
  169. package/dist/server/evaluate.js +61 -0
  170. package/dist/server/invalidation-index.d.ts +64 -0
  171. package/dist/server/invalidation-index.d.ts.map +1 -0
  172. package/dist/server/invalidation-index.js +0 -0
  173. package/dist/server/mutator.d.ts +59 -0
  174. package/dist/server/mutator.d.ts.map +1 -0
  175. package/dist/server/mutator.js +77 -0
  176. package/dist/server/query.d.ts +113 -0
  177. package/dist/server/query.d.ts.map +1 -0
  178. package/dist/server/query.js +35 -0
  179. package/dist/server/setup.d.ts +30 -0
  180. package/dist/server/setup.d.ts.map +1 -0
  181. package/dist/server/setup.js +107 -0
  182. package/dist/server/sql/setup.sql +215 -0
  183. package/dist/server/ssr.d.ts +29 -0
  184. package/dist/server/ssr.d.ts.map +1 -0
  185. package/dist/server/ssr.js +43 -0
  186. package/dist/server/sync-engine.d.ts +256 -0
  187. package/dist/server/sync-engine.d.ts.map +1 -0
  188. package/dist/server/sync-engine.js +805 -0
  189. package/dist/server/ws-server.d.ts +56 -0
  190. package/dist/server/ws-server.d.ts.map +1 -0
  191. package/dist/server/ws-server.js +241 -0
  192. package/package.json +81 -0
@@ -0,0 +1,215 @@
1
+ -- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.
2
+ --
3
+ -- Design notes (see "Implementační zadání" §5.1 in the design doc):
4
+ --
5
+ -- The outbox is filled by a trigger, not by application code. That way *any*
6
+ -- writer — Prisma, a raw SQL migration, a psql session — produces change events,
7
+ -- and the application never has to remember to publish them.
8
+ --
9
+ -- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what
10
+ -- makes gap-free reading possible: a `bigserial` alone is not enough, because
11
+ -- sequence values are handed out before commit, so a reader ordering by `seq`
12
+ -- can walk past a row belonging to a transaction that commits later. Readers
13
+ -- therefore only consume rows whose `xid` is below the oldest in-flight
14
+ -- transaction id (see OutboxChangeSource).
15
+
16
+ CREATE TABLE IF NOT EXISTS nowity_outbox (
17
+ seq bigserial PRIMARY KEY,
18
+ xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
19
+ tbl text NOT NULL,
20
+ op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),
21
+ pk jsonb NOT NULL,
22
+ before jsonb,
23
+ after jsonb,
24
+ client_id text,
25
+ mutation_id bigint,
26
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()
27
+ );
28
+
29
+ CREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity_outbox (xid, seq);
30
+
31
+ -- Authorization epoch per scope (typically one project / tenant / workspace).
32
+ -- Bumped whenever a row in a permission table changes; every snapshot and patch
33
+ -- carries the epoch it was computed under.
34
+ --
35
+ -- `last_position` is what makes the bump happen once per *change* rather than
36
+ -- once per reader. Several sync processes see the same transaction and each
37
+ -- would otherwise increment this row, so one permission change would cost N
38
+ -- writes to one very hot row — and an at-least-once replay would inflate it on a
39
+ -- single process too.
40
+ CREATE TABLE IF NOT EXISTS nowity_scope_epoch (
41
+ scope text PRIMARY KEY,
42
+ version bigint NOT NULL DEFAULT 1,
43
+ last_position text
44
+ );
45
+
46
+ ALTER TABLE nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;
47
+
48
+ -- Where each sync process has read the outbox up to.
49
+ --
50
+ -- Only ever a retention watermark: a process that restarts resumes from the
51
+ -- current transaction horizon, never from here, so a cursor left behind by a
52
+ -- crashed node can hold rows back but can never make one skip a change.
53
+ CREATE TABLE IF NOT EXISTS nowity_consumer (
54
+ consumer_id text PRIMARY KEY,
55
+ cursor_xid xid8 NOT NULL,
56
+ updated_at timestamptz NOT NULL DEFAULT now()
57
+ );
58
+
59
+ -- Last mutation of each client the server has durably processed. Written in the
60
+ -- same transaction as the mutation itself, so it can never disagree with the
61
+ -- data.
62
+ --
63
+ -- `session_token` is which connection currently owns the id. Two connections
64
+ -- sharing one client id is a write-losing bug, and within a single process the
65
+ -- engine can see both and complain — with several sync processes neither can see
66
+ -- the other's sessions, and the collision is otherwise perfectly silent: both
67
+ -- sides keep numbering from one, each takes the other's mutation for a replay of
68
+ -- its own, and every second write is acknowledged and discarded. The token moves
69
+ -- that argument into the one place both processes share.
70
+ CREATE TABLE IF NOT EXISTS nowity_client (
71
+ client_id text PRIMARY KEY,
72
+ last_mutation_id bigint NOT NULL DEFAULT 0,
73
+ session_token text,
74
+ updated_at timestamptz NOT NULL DEFAULT now()
75
+ );
76
+
77
+ ALTER TABLE nowity_client ADD COLUMN IF NOT EXISTS session_token text;
78
+
79
+ -- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.
80
+ CREATE OR REPLACE FUNCTION nowity_capture() RETURNS trigger AS $$
81
+ DECLARE
82
+ v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);
83
+ v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;
84
+ v_after jsonb := CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END;
85
+ v_source jsonb := COALESCE(v_after, v_before);
86
+ v_pk jsonb;
87
+ BEGIN
88
+ SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk
89
+ FROM unnest(v_pk_cols) AS col;
90
+
91
+ INSERT INTO nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)
92
+ VALUES (
93
+ TG_TABLE_NAME,
94
+ lower(TG_OP),
95
+ v_pk,
96
+ v_before,
97
+ v_after,
98
+ NULLIF(current_setting('nowity.client_id', true), ''),
99
+ NULLIF(current_setting('nowity.mutation_id', true), '')::bigint
100
+ );
101
+
102
+ -- Wake the sync engine up at commit. The payload is intentionally tiny; it
103
+ -- is a doorbell, not a data channel (NOTIFY payloads are capped at 8000 B).
104
+ PERFORM pg_notify('nowity_change', TG_TABLE_NAME);
105
+
106
+ RETURN NULL; -- AFTER trigger, return value is ignored
107
+ END;
108
+ $$ LANGUAGE plpgsql;
109
+
110
+ -- Attach change capture to a table.
111
+ CREATE OR REPLACE FUNCTION nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])
112
+ RETURNS void AS $$
113
+ BEGIN
114
+ EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);
115
+ EXECUTE format(
116
+ 'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '
117
+ 'FOR EACH ROW EXECUTE FUNCTION nowity_capture(%L)',
118
+ p_table, p_pk
119
+ );
120
+ END;
121
+ $$ LANGUAGE plpgsql;
122
+
123
+ CREATE OR REPLACE FUNCTION nowity_untrack(p_table regclass) RETURNS void AS $$
124
+ BEGIN
125
+ EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);
126
+ END;
127
+ $$ LANGUAGE plpgsql;
128
+
129
+ -- The single-argument form is gone: left in place it would be an overload of the
130
+ -- one below, and `nowity_bump_epoch($1)` would stop resolving.
131
+ DROP FUNCTION IF EXISTS nowity_bump_epoch(text);
132
+
133
+ -- Increment the authorization epoch of a scope and return the current value.
134
+ --
135
+ -- With a position, the increment happens only the first time that position is
136
+ -- seen for the scope. Whichever process gets there first does the write and the
137
+ -- rest read the same answer, because the `ON CONFLICT` takes a row lock and they
138
+ -- queue behind it.
139
+ --
140
+ -- Skipping the increment on a replay is not a missed invalidation: the epoch had
141
+ -- already moved when the position was first handled, and a process replaying it
142
+ -- still recomputes its subscriptions and stamps them with the value it reads
143
+ -- here.
144
+ CREATE OR REPLACE FUNCTION nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)
145
+ RETURNS bigint AS $$
146
+ DECLARE
147
+ v_version bigint;
148
+ BEGIN
149
+ INSERT INTO nowity_scope_epoch (scope, version, last_position)
150
+ VALUES (p_scope, 1, p_position)
151
+ ON CONFLICT (scope) DO UPDATE
152
+ SET version = nowity_scope_epoch.version
153
+ + CASE
154
+ WHEN p_position IS NULL THEN 1
155
+ WHEN nowity_scope_epoch.last_position IS DISTINCT FROM p_position THEN 1
156
+ ELSE 0
157
+ END,
158
+ last_position = COALESCE(p_position, nowity_scope_epoch.last_position)
159
+ RETURNING version INTO v_version;
160
+ RETURN v_version;
161
+ END;
162
+ $$ LANGUAGE plpgsql;
163
+
164
+ -- Record how far a consumer has read, for retention only.
165
+ CREATE OR REPLACE FUNCTION nowity_consumer_seen(p_consumer text, p_cursor text)
166
+ RETURNS void AS $$
167
+ BEGIN
168
+ INSERT INTO nowity_consumer (consumer_id, cursor_xid)
169
+ VALUES (p_consumer, p_cursor::xid8)
170
+ ON CONFLICT (consumer_id) DO UPDATE
171
+ SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();
172
+ END;
173
+ $$ LANGUAGE plpgsql;
174
+
175
+ CREATE OR REPLACE FUNCTION nowity_consumer_forget(p_consumer text) RETURNS void AS $$
176
+ BEGIN
177
+ DELETE FROM nowity_consumer WHERE consumer_id = p_consumer;
178
+ END;
179
+ $$ LANGUAGE plpgsql;
180
+
181
+ -- Delete outbox rows every live consumer has already read.
182
+ --
183
+ -- "Live" is a wall-clock judgement, and it is the only unsafe part of retention:
184
+ -- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows
185
+ -- it had not reached may be deleted. It resumes from the transaction horizon
186
+ -- rather than from its old cursor, so it does not read a hole — it simply never
187
+ -- learns about those changes and its clients keep whatever they had until
188
+ -- something else touches it. Set the interval well above any pause a healthy
189
+ -- process can take.
190
+ --
191
+ -- With no live consumers at all this deletes nothing. An empty table means "the
192
+ -- readers have not registered yet", not "nobody will ever read this".
193
+ CREATE OR REPLACE FUNCTION nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')
194
+ RETURNS bigint AS $$
195
+ DECLARE
196
+ v_min xid8;
197
+ v_deleted bigint;
198
+ BEGIN
199
+ -- `ORDER BY … LIMIT 1` rather than `min()`: xid8 has the comparison
200
+ -- operators but not the aggregate.
201
+ SELECT cursor_xid INTO v_min
202
+ FROM nowity_consumer
203
+ WHERE updated_at > now() - p_stale_after
204
+ ORDER BY cursor_xid
205
+ LIMIT 1;
206
+
207
+ IF v_min IS NULL THEN
208
+ RETURN 0;
209
+ END IF;
210
+
211
+ DELETE FROM nowity_outbox WHERE xid <= v_min;
212
+ GET DIAGNOSTICS v_deleted = ROW_COUNT;
213
+ RETURN v_deleted;
214
+ END;
215
+ $$ LANGUAGE plpgsql;
@@ -0,0 +1,29 @@
1
+ import type { HydrationPayload } from "../core/protocol";
2
+ import type { SnapshotRunner } from "./db";
3
+ import type { QueryRegistry, SessionInfo } from "./query";
4
+ export type { HydrationPayload };
5
+ export interface InitialDataRequest {
6
+ query: string;
7
+ args?: unknown;
8
+ }
9
+ export interface ReadInitialDataOptions {
10
+ snapshots: SnapshotRunner;
11
+ queries: QueryRegistry;
12
+ session: SessionInfo;
13
+ requests: InitialDataRequest[];
14
+ }
15
+ /**
16
+ * Run live queries once, on the server, for the first render.
17
+ *
18
+ * This is the `Database → Server Component → initialProps → MobX store` step of
19
+ * the design: the first paint has real data without waiting for a WebSocket to
20
+ * open. It is an optimisation, not a requirement — the client subscribes to the
21
+ * same queries anyway and replaces the payload with an authoritative snapshot.
22
+ *
23
+ * All requests share one read snapshot, so a page rendered from several queries
24
+ * cannot show a torn state. Authorization is the same check the sync engine runs;
25
+ * a denied query yields an empty payload rather than an error, because a page
26
+ * usually still renders without one of its panels.
27
+ */
28
+ export declare function readInitialData(opts: ReadInitialDataOptions): Promise<HydrationPayload[]>;
29
+ //# sourceMappingURL=ssr.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr.d.ts","sourceRoot":"","sources":["../../src/server/ssr.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,MAAM,CAAC;AAE5D,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE1D,YAAY,EAAE,gBAAgB,EAAE,CAAC;AAEjC,MAAM,WAAW,kBAAkB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,sBAAsB;IACnC,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,aAAa,CAAC;IACvB,OAAO,EAAE,WAAW,CAAC;IACrB,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAClC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,sBAAsB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAQ/F"}
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readInitialData = readInitialData;
4
+ const evaluate_1 = require("./evaluate");
5
+ /**
6
+ * Run live queries once, on the server, for the first render.
7
+ *
8
+ * This is the `Database → Server Component → initialProps → MobX store` step of
9
+ * the design: the first paint has real data without waiting for a WebSocket to
10
+ * open. It is an optimisation, not a requirement — the client subscribes to the
11
+ * same queries anyway and replaces the payload with an authoritative snapshot.
12
+ *
13
+ * All requests share one read snapshot, so a page rendered from several queries
14
+ * cannot show a torn state. Authorization is the same check the sync engine runs;
15
+ * a denied query yields an empty payload rather than an error, because a page
16
+ * usually still renders without one of its panels.
17
+ */
18
+ async function readInitialData(opts) {
19
+ return opts.snapshots.withSnapshot(async (snap) => {
20
+ const payloads = [];
21
+ for (const request of opts.requests) {
22
+ payloads.push(await readOne(snap, opts, request));
23
+ }
24
+ return payloads;
25
+ });
26
+ }
27
+ async function readOne(snap, opts, request) {
28
+ const def = opts.queries.get(request.query);
29
+ const args = request.args ?? {};
30
+ const ctx = { db: snap, session: opts.session };
31
+ const scope = def.scope ? def.scope(args, ctx) : null;
32
+ const epoch = scope ? await readEpoch(snap, scope) : 0;
33
+ const base = { query: request.query, args, entity: def.entity, scope, epoch };
34
+ if (def.authorize && !(await def.authorize(args, ctx))) {
35
+ return { ...base, ids: [], rows: [], denied: true };
36
+ }
37
+ const output = await (0, evaluate_1.evaluateQuery)(def, args, opts.session, snap);
38
+ return { ...base, ids: output.ids, ...(0, evaluate_1.outputRows)(output) };
39
+ }
40
+ async function readEpoch(snap, scope) {
41
+ const { rows } = await snap.query(`SELECT version::text AS version FROM nowity_scope_epoch WHERE scope = $1`, [scope]);
42
+ return rows.length ? Number(rows[0].version) : 0;
43
+ }
@@ -0,0 +1,256 @@
1
+ import { type ServerMessage, type ServerWelcome } from "../core/protocol";
2
+ import { type ChangeEvent, type ReadKeySet } from "../core/types";
3
+ import type { ChangeSource } from "./change-source/change-source";
4
+ import type { SnapshotRunner } from "./db";
5
+ import { type QueryOutput } from "./evaluate";
6
+ import { type MutatorRegistry, type WriteRunner } from "./mutator";
7
+ import type { QueryDef, QueryRegistry, SessionInfo } from "./query";
8
+ export interface SyncEngineOptions {
9
+ snapshots: SnapshotRunner;
10
+ writes: WriteRunner;
11
+ source: ChangeSource;
12
+ queries: QueryRegistry;
13
+ mutators: MutatorRegistry;
14
+ /**
15
+ * Tables that carry authorization, not client data — `ProjectMember`,
16
+ * `Project`, role tables. A change in one of them is an *invalidation*, never
17
+ * a patch (§2 of the design doc).
18
+ */
19
+ permissionTables?: string[];
20
+ /**
21
+ * Authorization scope(s) invalidated by a change in a permission table.
22
+ * Returning null means "cannot tell" — then every subscription is
23
+ * revalidated, which is slow but never wrong.
24
+ */
25
+ scopeOfChange?: (event: ChangeEvent) => string | string[] | null;
26
+ /** API shape announced in the handshake, when the class-based API is in use. */
27
+ api?: ServerWelcome["api"];
28
+ /**
29
+ * Whether a subscription may be watched by row rather than by table.
30
+ *
31
+ * On by default, and the only reason to turn it off is to find out whether a
32
+ * subscription that stopped updating did so because of the narrowing. With
33
+ * it off every subscription is woken by any change to a table it read, which
34
+ * is what the engine did before read keys existed: slower by a factor of
35
+ * however many subscriptions share a table, and impossible to get wrong.
36
+ */
37
+ narrowInvalidation?: boolean;
38
+ onError?: (err: Error) => void;
39
+ }
40
+ interface Subscription {
41
+ subId: string;
42
+ def: QueryDef;
43
+ args: unknown;
44
+ scope: string | null;
45
+ epoch: number;
46
+ prev: QueryOutput;
47
+ session: EngineSession;
48
+ /**
49
+ * Tables whose change may affect this subscription.
50
+ *
51
+ * `null` means "not known yet" and is deliberately the pessimistic value:
52
+ * the subscription is then revalidated on every transaction. A read set that
53
+ * is merely incomplete produces a subscription that silently stops updating,
54
+ * which is the one failure mode worth spending work to avoid.
55
+ */
56
+ tables: Set<string> | null;
57
+ /**
58
+ * The same dependency, narrowed to rows wherever the query said which ones.
59
+ *
60
+ * This is what the {@link InvalidationIndex} files the subscription under,
61
+ * and `null` carries the same pessimistic meaning as it does for `tables`.
62
+ * A table present in `tables` but absent here is watched whole.
63
+ */
64
+ keys: ReadKeySet | null;
65
+ /** Entity of the rows, once an execution has told us. */
66
+ entity: string;
67
+ /**
68
+ * The client is currently not allowed to see this query.
69
+ *
70
+ * Denied subscriptions stay registered on purpose. They receive no data
71
+ * whatsoever (that is the "zombie subscription" guarantee, test 3), but they
72
+ * are still revalidated when their scope's epoch moves — which is what makes
73
+ * *gaining* access work (test 2): nothing in the data changes when a user is
74
+ * added to a project, so the only thing that can wake the subscription up is
75
+ * the invalidation.
76
+ */
77
+ denied: boolean;
78
+ }
79
+ /** Server-side handle for one connected client. */
80
+ export declare class EngineSession {
81
+ readonly info: SessionInfo;
82
+ readonly send: (msg: ServerMessage) => void;
83
+ readonly subs: Map<string, Subscription>;
84
+ /**
85
+ * This connection's claim on its client id, once the handshake has made it.
86
+ *
87
+ * Null until then, which is why a session opened without a handshake — the
88
+ * performance harness does exactly that — is not subject to the check.
89
+ */
90
+ token: string | null;
91
+ /** Highest `lastMutationId` already communicated to this client. */
92
+ lastSentMutationId: number;
93
+ /** Serialises this client's mutations; they must be applied in order. */
94
+ mutationChain: Promise<unknown>;
95
+ closed: boolean;
96
+ constructor(info: SessionInfo, send: (msg: ServerMessage) => void);
97
+ }
98
+ /**
99
+ * "Somebody else is this client now."
100
+ *
101
+ * A refusal of the connection, not of the write, and the difference decides
102
+ * whether the mutation id may be burned.
103
+ */
104
+ export declare class ClientIdTaken extends Error {
105
+ readonly nowity: "client-id-taken";
106
+ constructor(message: string);
107
+ }
108
+ export interface MutationOutcome {
109
+ ok: boolean;
110
+ error?: string;
111
+ lastMutationId: number;
112
+ }
113
+ /**
114
+ * The sync engine: turns change events into per-subscription patches.
115
+ *
116
+ * Everything that touches subscription state runs on one serialised task queue —
117
+ * change batches, new subscriptions, teardown. That is not just for tidiness, it
118
+ * is what closes the snapshot/stream hole (§6, test 9): a subscription's initial
119
+ * snapshot can only be read while the stream is quiesced at a known cursor, and
120
+ * the cursor's meaning ("every transaction up to here had already finished") then
121
+ * guarantees the snapshot contains everything the stream will not replay.
122
+ */
123
+ export declare class SyncEngine {
124
+ private readonly opts;
125
+ private readonly permissionTables;
126
+ private readonly sessions;
127
+ private readonly onError;
128
+ /**
129
+ * Which subscriptions a change can reach.
130
+ *
131
+ * The engine never walks every subscription of every session any more; it
132
+ * asks this instead, and walks the answer.
133
+ */
134
+ private readonly index;
135
+ /**
136
+ * scope → subscriptions in it, for the permission path.
137
+ *
138
+ * A scope invalidation is not a row change and cannot be looked up by value:
139
+ * the whole point is that nothing in the *data* moved.
140
+ */
141
+ private readonly byScope;
142
+ private tasks;
143
+ private started;
144
+ /**
145
+ * What the fan-out actually cost, for anyone measuring it.
146
+ *
147
+ * `evaluations` is the number the whole design turns on: how many times a
148
+ * live query had to be run against the database. Without it a regression
149
+ * here looks like nothing at all until the process is under load.
150
+ */
151
+ readonly stats: {
152
+ batches: number;
153
+ candidates: number;
154
+ evaluations: number;
155
+ fanOutMs: number;
156
+ };
157
+ /** See {@link SyncEngineOptions.narrowInvalidation}. */
158
+ private readonly narrow;
159
+ constructor(opts: SyncEngineOptions);
160
+ start(): Promise<void>;
161
+ stop(): Promise<void>;
162
+ /** Wait until every queued task (and the change stream) has settled. */
163
+ settle(): Promise<void>;
164
+ /** Serialised execution of everything that reads or writes subscription state. */
165
+ private run;
166
+ openSession(info: SessionInfo, send: (msg: ServerMessage) => void): EngineSession;
167
+ closeSession(session: EngineSession): Promise<void>;
168
+ welcome(session: EngineSession): Promise<void>;
169
+ /**
170
+ * Take ownership of the client id for this connection.
171
+ *
172
+ * The newest connection wins, which is what a reconnect needs: the socket
173
+ * that just arrived is the one the user is looking at. A connection that has
174
+ * been superseded finds out at its next write, and finds out loudly instead
175
+ * of having it silently dropped.
176
+ */
177
+ private claimClientId;
178
+ subscribe(session: EngineSession, subId: string, queryName: string, args: unknown): Promise<void>;
179
+ unsubscribe(session: EngineSession, subId: string): Promise<void>;
180
+ /**
181
+ * File a subscription under what it reads, and under its scope.
182
+ *
183
+ * Idempotent: `add` replaces any previous placement, which is what makes it
184
+ * safe to call again every time a re-execution reports a different read set.
185
+ */
186
+ private register;
187
+ /**
188
+ * What the subscription is filed under, once the kill switch has had its say.
189
+ *
190
+ * Dropping to table granularity here rather than at extraction time keeps
191
+ * the two paths one path: the keys are still derived, still tested, and the
192
+ * switch only decides how much of them the index is allowed to use.
193
+ */
194
+ private filedKeys;
195
+ private forget;
196
+ /** `handleBatch`, with the one number worth watching taken around it. */
197
+ private timedBatch;
198
+ private handleBatch;
199
+ /**
200
+ * Sessions whose mutation watermark this batch may have moved.
201
+ *
202
+ * A client's `last_mutation_id` only advances when one of its own mutations
203
+ * commits, and a mutation that wrote nothing produces no batch at all — so
204
+ * when the source stamps its events, the clients named in a batch are the
205
+ * only ones with news in it. A source that cannot attribute writes gets the
206
+ * honest answer, which is every session.
207
+ */
208
+ private writersIn;
209
+ /**
210
+ * The subscriptions this batch could have changed the answer for.
211
+ *
212
+ * Everything else is skipped without touching the database, which is the
213
+ * whole difference between a cost that grows with the number of changes and
214
+ * one that grows with the number of changes times the number of watchers.
215
+ */
216
+ private candidatesFor;
217
+ /**
218
+ * Take an execution's read set and entity, and make them the subscription's.
219
+ *
220
+ * The read set is re-derived on every execution rather than accumulated,
221
+ * because a query can legitimately ask a different question each time — a
222
+ * method that branches, or a list whose window moved. Accumulating would
223
+ * leave the subscription filed under rows it no longer looks at, and the
224
+ * index would fill up with entries nothing can ever remove.
225
+ */
226
+ private absorb;
227
+ private rememberRefusedReads;
228
+ /**
229
+ * One pass over a read-set-tracking subscription, in whichever direction it
230
+ * moved: granted, revoked, or merely changed.
231
+ */
232
+ private refreshTracked;
233
+ private reauthorizeAndResnapshot;
234
+ private patchFor;
235
+ /** Diff a fresh output against the subscription's previous one and adopt it. */
236
+ private diffInto;
237
+ private evaluate;
238
+ private toSnapshot;
239
+ /** Queue a mutation; mutations of one client are applied in order. */
240
+ mutate(session: EngineSession, mutationId: number, name: string, args: unknown): Promise<MutationOutcome>;
241
+ private executeMutation;
242
+ /**
243
+ * Move a scope's epoch on, once per change rather than once per reader.
244
+ *
245
+ * `position` is what makes several sync processes agree: they all hand over
246
+ * the same batch position, the first one through does the increment and the
247
+ * rest read the value it wrote. Without it, one permission change would cost
248
+ * a write per node on a single very hot row.
249
+ */
250
+ private bumpEpoch;
251
+ private readEpoch;
252
+ private readLastMutationId;
253
+ private readLastMutationIds;
254
+ }
255
+ export {};
256
+ //# sourceMappingURL=sync-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-engine.d.ts","sourceRoot":"","sources":["../../src/server/sync-engine.ts"],"names":[],"mappings":"AAGA,OAAO,EAEH,KAAK,aAAa,EAClB,KAAK,aAAa,EAIrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAGH,KAAK,WAAW,EAEhB,KAAK,UAAU,EAElB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,MAAM,CAAC;AAC5D,OAAO,EAA0C,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AACtF,OAAO,EAAoB,KAAK,eAAe,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AACrF,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,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