@ultimat3/realtime 31.45.0 → 31.47.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.
package/README.md CHANGED
@@ -18,15 +18,39 @@ Tier 2 covers ~90% of "make it realtime". Tier 3 buys exactly one extra property
18
18
 
19
19
  ```ts
20
20
  // query
21
+ import { mutator, t } from '@ultimat3/action';
22
+ import { database, entity, integer, timestamp, uuid } from '@ultimat3/entity';
23
+ import { can } from '@ultimat3/policy';
24
+ import { from, query } from '@ultimat3/query';
25
+
26
+ const posts = entity('posts', {
27
+ tenant: 'orgId',
28
+ columns: {
29
+ id: uuid().primaryKey(),
30
+ orgId: uuid(),
31
+ likeCount: integer().default(0),
32
+ createdAt: timestamp().defaultNow(),
33
+ },
34
+ });
35
+ const db = database({ posts });
36
+ type Post = typeof posts.$row;
37
+
21
38
  export const liveFeed = query({
22
39
  input: t.object({ orgId: t.uuid }),
23
40
  policy: can('feed:read'),
24
41
  live: true,
25
- sql: ({ orgId }) => db.posts.where({ orgId }).orderBy('createdAt').limit(50),
42
+ sql: ({ orgId }) =>
43
+ from<Post>('posts', () => db.posts.where({ orgId }).all())
44
+ .where({ orgId })
45
+ .orderBy('createdAt')
46
+ .limit(50),
26
47
  });
27
48
 
28
49
  // mutator (action + optimistic local twin)
29
50
  export const likePost = mutator({
51
+ input: t.object({ postId: t.uuid }),
52
+ output: t.object({ likeCount: t.number.int(), likedByMe: t.boolean }),
53
+ policy: can('post:like'),
30
54
  // REQUIRED (`X_MUTATOR_NOT_IDEMPOTENT`): a replay under the same Idempotency-Key answers the
31
55
  // first result instead of running `server` again.
32
56
  idempotent: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/realtime",
3
- "version": "31.45.0",
3
+ "version": "31.47.0",
4
4
  "description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -52,10 +52,10 @@
52
52
  "test": "bun test"
53
53
  },
54
54
  "dependencies": {
55
- "@ultimat3/core": "31.45.0",
56
- "@ultimat3/entity": "31.45.0",
57
- "@ultimat3/policy": "31.45.0",
58
- "@ultimat3/query": "31.45.0",
55
+ "@ultimat3/core": "31.47.0",
56
+ "@ultimat3/entity": "31.47.0",
57
+ "@ultimat3/policy": "31.47.0",
58
+ "@ultimat3/query": "31.47.0",
59
59
  "nats": "2.29.3"
60
60
  }
61
61
  }
@@ -9,6 +9,7 @@ import type { ClientScope, RecordRows, Row } from '@ultimat3/core/page';
9
9
  import {
10
10
  finiteOption,
11
11
  isJsonObject,
12
+ principalScopeName,
12
13
  renderThrowable,
13
14
  type UltimateError,
14
15
  } from '@ultimat3/core/page';
@@ -50,12 +51,12 @@ export interface LocalStore {
50
51
 
51
52
  /**
52
53
  * The storage key of a principal, or `undefined` for an UNSCOPED page (rendered for nobody):
53
- * nothing is persisted there, because there is no principal to key it by. Prefixed so a principal
54
- * spelled `anon` can never share the anonymous visitor's rows.
54
+ * nothing is persisted there, because there is no principal to key it by. Core spells the rest,
55
+ * because a replay names its queue's owner to the server in this same token.
55
56
  */
56
57
  export function scopeKey(principal: ClientScope['principal']): string | undefined {
57
58
  if (principal === undefined) return undefined;
58
- return principal === null ? 'anon' : `p:${principal}`;
59
+ return principalScopeName(principal);
59
60
  }
60
61
 
61
62
  const RECORDS = 'records';
@@ -1,18 +1,23 @@
1
1
  /**
2
2
  * The page's ONE outbox: writes a page could not send, persisted under the current principal and
3
3
  * replayed IN ORDER over HTTP, each under its own idempotency key. AT LEAST once — an entry leaves
4
- * the disk when its ack is written. A principal change abandons the pass and wipes the queue.
4
+ * the disk when its ack is written. A principal change abandons the pass and wipes the queue; a
5
+ * session this page cannot see change (another tab) is refused by the server and the entry waits.
5
6
  */
6
7
 
7
8
  import type { ClientScope, UltimateError } from '@ultimat3/core/page';
8
9
  import {
10
+ CLIENT_REPLAY_SCOPE_HEADER,
9
11
  classifyThrown,
10
12
  clientTransport,
11
13
  finiteCount,
14
+ isSessionRefusalCode,
15
+ isUltimateError,
12
16
  OUTBOX_DRAIN_MESSAGE,
13
17
  onRescope,
14
18
  pageClient,
15
19
  renderThrowable,
20
+ stringField,
16
21
  } from '@ultimat3/core/page';
17
22
  import type { LocalStore } from './local-store-idb';
18
23
  import { pageLocalStore, scopeKey } from './local-store-idb';
@@ -58,8 +63,11 @@ export interface OutboxOptions {
58
63
  /**
59
64
  * One write, over HTTP. Default: `clientTransport` to the entry's pin or `actionPath(entry.name)` (`pinned-wire.ts`), adding every
60
65
  * record the answer carried (`type:key`) to `carried` — what its overlay settles against.
66
+ * `scope` is the queue's owner (`scopeKey`), which the request must name; none on an unscoped page.
61
67
  */
62
- readonly send?: ((entry: OutboxEntry, carried: Set<string>) => Promise<unknown>) | undefined;
68
+ readonly send?:
69
+ | ((entry: OutboxEntry, carried: Set<string>, scope: string | undefined) => Promise<unknown>)
70
+ | undefined;
63
71
  readonly overlays?: (() => OutboxOverlays | undefined) | undefined;
64
72
  /**
65
73
  * Runs, and is awaited, before a write is queued. The boot hands it the record persister's
@@ -84,10 +92,29 @@ export interface OutboxOptions {
84
92
 
85
93
  const EMPTY: DrainReport = { sent: 0, collapsed: 0, remaining: 0, stoppedAt: null };
86
94
 
87
- /** One principal's open queue, and the scope the drain lock is named after. */
95
+ /**
96
+ * One principal's open queue, and its scope: what the drain lock is named after and what every
97
+ * replay names as its owner. The queue a write sits in IS its binding, so an entry written by a
98
+ * build older than the header is bound too, with nothing to migrate.
99
+ */
88
100
  interface Held {
89
101
  readonly queue: OfflineQueue;
90
102
  readonly scope: string | undefined;
103
+ /** A signed-in principal's: only such a queue can have its session go missing. */
104
+ readonly signedIn: boolean;
105
+ }
106
+
107
+ /** `@ultimat3/action`'s refusal of a replay under a session that is not the queue's owner. */
108
+ const NOT_THE_OWNER = 'X_REPLAY_PRINCIPAL_MISMATCH';
109
+
110
+ /**
111
+ * The server said who is asking, and it is not who queued this: says nothing about the write, so
112
+ * it stays queued for its owner. Never `fail`: that would drop a write nobody refused.
113
+ */
114
+ function ownerIsAbsent(error: unknown, signedIn: boolean): boolean {
115
+ const code = stringField(error, 'code');
116
+ if (code === undefined) return false;
117
+ return code === NOT_THE_OWNER || (signedIn && isSessionRefusalCode(code));
91
118
  }
92
119
 
93
120
  export function localOutbox(options: OutboxOptions): PageOutbox {
@@ -151,7 +178,8 @@ export function localOutbox(options: OutboxOptions): PageOutbox {
151
178
  /** Never rejects: a queue the disk would not open is a memory queue, said once by code. */
152
179
  const open = async (): Promise<void> => {
153
180
  const at = epoch;
154
- const scope = scopeKey(principal());
181
+ const who = principal();
182
+ const scope = scopeKey(who);
155
183
  let queue: OfflineQueue;
156
184
  try {
157
185
  queue = await OfflineQueue.open(queueStore(await options.local, scope), ceiling);
@@ -166,7 +194,7 @@ export function localOutbox(options: OutboxOptions): PageOutbox {
166
194
  return;
167
195
  }
168
196
  held?.queue.abandon();
169
- held = { queue, scope };
197
+ held = { queue, scope, signedIn: typeof who === 'string' };
170
198
  notify();
171
199
  };
172
200
  let ready = open();
@@ -183,17 +211,22 @@ export function localOutbox(options: OutboxOptions): PageOutbox {
183
211
  let again = false;
184
212
 
185
213
  const deliver =
186
- ({ queue, scope }: Held) =>
214
+ ({ queue, scope, signedIn }: Held) =>
187
215
  async (mutation: QueuedMutation): Promise<void> => {
188
216
  const carried = new Set<string>();
189
217
  try {
190
218
  const { key, name, input, http } = mutation;
191
- await send({ key, name, input, ...(http === undefined ? {} : { http }) }, carried);
219
+ await send({ key, name, input, ...(http === undefined ? {} : { http }) }, carried, scope);
192
220
  } catch (error) {
193
221
  const kind = classifyThrown(error);
194
- // The network, or a server asking to be asked again: stays queued, and the pass stops so
195
- // nothing behind it overtakes it. So does a queue whose principal left mid-send.
196
- if (kind === 'retryable' || kind === 'retry-after' || queue.abandoned) throw error;
222
+ const absent = ownerIsAbsent(error, signedIn);
223
+ if (absent && !queue.abandoned && isUltimateError(error)) warn(error);
224
+ // The network, a server asking to be asked again, or a session that is not this queue's
225
+ // owner: stays queued, and the pass stops so nothing behind it overtakes it. So does a
226
+ // queue whose principal left mid-send.
227
+ if (absent || kind === 'retryable' || kind === 'retry-after' || queue.abandoned) {
228
+ throw error;
229
+ }
197
230
  // Anything else is the server's decision about this write — kept for the UI, never resent.
198
231
  await queue.fail(mutation.key, toQueueError(error));
199
232
  notify();
@@ -387,13 +420,19 @@ function exclusive<T>(name: string, work: () => Promise<T>): Promise<T> {
387
420
 
388
421
  const LOCAL_LOCKS: unique symbol = Symbol.for('ultimate.outbox-locks');
389
422
  type LockHost = { [LOCAL_LOCKS]?: Map<string, Promise<unknown>> };
390
- async function sendOverHttp(entry: OutboxEntry, carried: Set<string>): Promise<unknown> {
423
+ async function sendOverHttp(
424
+ entry: OutboxEntry,
425
+ carried: Set<string>,
426
+ scope: string | undefined,
427
+ ): Promise<unknown> {
391
428
  const wire = mutationWire(entry.name, entry.input, entry.http);
392
429
  return await clientTransport({
393
430
  method: wire.method,
394
431
  url: wire.url,
395
432
  body: wire.body,
396
433
  idempotencyKey: entry.key,
434
+ // The cookie is whoever signed in last, in any tab; this says who the write is for.
435
+ ...(scope === undefined ? {} : { headers: { [CLIENT_REPLAY_SCOPE_HEADER]: scope } }),
397
436
  onEnvelope: (envelope) => carriedBy(envelope, carried),
398
437
  });
399
438
  }