@ultimat3/realtime 31.60.0 → 31.61.1

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
@@ -98,7 +98,7 @@ class — stay on `.`.
98
98
 
99
99
  | Concern | Entry | Export |
100
100
  |---|---|---|
101
- | tier 1 | `./server` | `ChannelHub`, `PresenceRegistry`, `SyncSocket`, `SocketRegistry`; `publishChannelEvent` — a channel event from a job or an action, on the bus the boot installed |
101
+ | tier 1 | `./server` | `ChannelHub`, `PresenceRegistry`, `SyncSocket`, `SocketRegistry`; `publishChannelEvent` — a channel event from a job or an action, on the bus the boot installed; `subscribeChannelEvents`, `nextChannelEvent` — server code hearing one |
102
102
  | a bus driver | `./adapter` | `Transport` and its parts (`TransportHandler`, `TransportSet`, `TransportSetEntry`, `TransportSubscription`), the errors a driver throws (`TransportUnavailableError`, also on `.`; `TransportProtocolError`, only on this entry), and `installChannelTransport` — the boot's installer and `@ultimat3/testing`'s seam, on no other entry. The offline stores (`LocalStore` / `openLocalStore` / `pageLocalStore` / `memoryLocalStore()`, `QueueStore` / `memoryQueueStore()`, `RecordStoreOptions`, `SignalFactory`) are on `.`: no `runtime.ts` field takes one. An app hands its bus to `transport` in `apps/<app>/runtime.ts`, never to the installer |
103
103
  | tier 2 | `./server` | `LiveQueryRegistry`, its resume-cursor events `CursorDistrusted` / `CursorTrustOptions` (`onUnsignedCursor`, `onCursorRefused`), `memoryChangeFeed()`, `postgresChangeFeed()`, `selectChangeFeed`, `changeFeedReplicator`, `postgresAdvisoryLock()`, `matcherFor` |
104
104
  | replication | `./server` | `parsePgUrl`, `bunPgStream`, `entityRow`, `changeLsn`, `commitPositionOf` |
@@ -196,8 +196,44 @@ export const announce = (orgId: string, id: string): Promise<void> =>
196
196
  | who delivers | every `sync` node bridged to that topic, to its members' `onEvent`. Under `x dev` the node is in this process and shares the bus; across processes the bus is NATS (`NATS_URL` set) or the app's own (`transport` in `apps/<app>/runtime.ts`) |
197
197
  | after COMMIT | nothing here can see a transaction: an event sent from inside one is on every page before a rollback |
198
198
  | at-most-once | never stored, never replayed — a member that was offline does not get it. Send "re-read", never state. A bus that refuses the send rejects (`X_TRANSPORT_UNAVAILABLE`); catch it where an event is not worth failing the write for |
199
- | nothing booted | a unit test or a bare script publishes onto a heap bus nobody hears, and does not throw. A test that wants delivery swaps the bus through `@ultimat3/testing`'s override seam, which installs the bus its `ChannelHub` holds and releases it after |
199
+ | nothing booted | a unit test or a bare script publishes onto a heap bus no node hears (only a `subscribeChannelEvents` in the same process), and does not throw. A test that wants delivery swaps the bus through `@ultimat3/testing`'s override seam, which installs the bus its `ChannelHub` holds and releases it after |
200
200
  | `realtime.enabled: false` | still safe to call: the bus exists, no node subscribes |
201
+
202
+ ### Waiting for an event in server code
203
+
204
+ `subscribeChannelEvents` hears the same frames on the same bus, in any role: an action that holds a
205
+ call open until a worker in another process moves what it waits on. Under NATS every node hears
206
+ every publish; under `x dev` the bus is the process's own.
207
+
208
+ ```ts
209
+ import { allow } from '@ultimat3/policy';
210
+ import { channel } from '@ultimat3/realtime';
211
+ import { nextChannelEvent } from '@ultimat3/realtime/server';
212
+
213
+ const opsFeed = channel('ops-feed', {
214
+ params: ['orgId'],
215
+ catchUp: { name: 'opsFeed' },
216
+ events: true,
217
+ policy: allow('public'),
218
+ });
219
+
220
+ // Answers the event, or null once 2 s pass; aborting rejects with the signal's reason.
221
+ // Either way, read the state again: an event says "re-read", and null is not "nothing changed".
222
+ export const awaitOperation = (orgId: string, operationId: string, signal: AbortSignal) =>
223
+ nextChannelEvent(opsFeed, { orgId }, {
224
+ timeoutMs: 2_000,
225
+ signal,
226
+ match: (event) => event['id'] === operationId,
227
+ });
228
+ ```
229
+
230
+ | Fact | Rule |
231
+ |---|---|
232
+ | `subscribeChannelEvents(decl, params, handler)` | resolves once the bus HOLDS the subscription, so a publish after the await is heard; answers `{ unsubscribe(), [Symbol.dispose] }` — `using sub = await …` ends it with the scope. Nothing is delivered after `unsubscribe()` |
233
+ | `nextChannelEvent(decl, params, { timeoutMs, signal?, match? })` | the first event `match` accepts (every event without one), else `null` at `timeoutMs`, counted from the open (`0` or less: `null` as soon as it is open). An abort — even mid-open — rejects with the signal's reason, a throwing `match` with its error; the first outcome wins and the listen closes however the wait ends |
234
+ | race-free waits | subscribe first, read the state, then wait — a change between the read and the subscribe is otherwise missed |
235
+ | refusals | the publish's own: `X_CHANNEL_DECLARATION_INVALID` on a channel without `events: true`, `X_TOPIC_FORBIDDEN` on a param that is no topic segment |
236
+ | at-most-once | an event published while nothing listened, or during a bus reconnect, is never heard: the caller's deadline and re-read are what make the wait correct, the event only makes it fast |
201
237
  | refusals | `X_CHANNEL_DECLARATION_INVALID` on a channel declared without `events: true`; `X_TOPIC_FORBIDDEN` for a param that is no topic segment |
202
238
  | no replicator | a node that serves no `live: true` query and no `records` channel reads no change, boots `live=none` on a real database, and is never `X_REALTIME_TOPOLOGY` |
203
239
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/realtime",
3
- "version": "31.60.0",
3
+ "version": "31.61.1",
4
4
  "description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -55,10 +55,10 @@
55
55
  "test": "bun test"
56
56
  },
57
57
  "dependencies": {
58
- "@ultimat3/core": "31.60.0",
59
- "@ultimat3/entity": "31.60.0",
60
- "@ultimat3/policy": "31.60.0",
61
- "@ultimat3/query": "31.60.0",
58
+ "@ultimat3/core": "31.61.1",
59
+ "@ultimat3/entity": "31.61.1",
60
+ "@ultimat3/policy": "31.61.1",
61
+ "@ultimat3/query": "31.61.1",
62
62
  "nats": "2.29.3"
63
63
  }
64
64
  }
@@ -48,6 +48,9 @@ export function installChannelTransport(transport: Transport): () => void {
48
48
  return installed.install(transport);
49
49
  }
50
50
 
51
+ /** The bus a publish goes out on right now — and so the one `subscribeChannelEvents` listens on. */
52
+ export const channelTransport = (): Transport => installed.current();
53
+
51
54
  /**
52
55
  * An ephemeral event to every member of `declared`'s topic for `params`, on every node — from any
53
56
  * process the framework booted. Never stored and never replayed: a member that was offline does not
@@ -0,0 +1,118 @@
1
+ // Server code hearing a channel's `events` frames on the bus the boot installed — the other half of
2
+ // `publishChannelEvent`. A process that serves no socket (an action holding a call open, a job)
3
+ // waits for an event another process published, on the same subject the `sync` node bridges.
4
+
5
+ import { assertCoded } from '@ultimat3/core';
6
+ import type { Channel } from './channel-decl';
7
+ import { channelSubject, channelTransport } from './channel-publish';
8
+ import type { JsonObject } from './json';
9
+ import { decode } from './sync-protocol';
10
+
11
+ /** An open listen: `unsubscribe()` (idempotent) or `using`. Nothing is delivered after either. */
12
+ export interface ChannelEventSubscription extends Disposable {
13
+ unsubscribe(): void;
14
+ }
15
+
16
+ /**
17
+ * Calls `handler` with each event published on `declared`'s topic for `params` — from this process
18
+ * or, under NATS, any node — until the subscription is closed. Resolves once the bus holds the
19
+ * subscription, so an event published after the await is heard: subscribe FIRST, then read the
20
+ * state, then wait. At-most-once and never replayed, as the publish is: an event only says
21
+ * "re-read", so a caller re-reads after one, and after its own deadline too.
22
+ */
23
+ export async function subscribeChannelEvents<K extends string>(
24
+ declared: Channel<K>,
25
+ params: Readonly<Record<K, string>>,
26
+ handler: (event: JsonObject) => void,
27
+ ): Promise<ChannelEventSubscription> {
28
+ assertCoded(
29
+ declared.events,
30
+ 'X_CHANNEL_DECLARATION_INVALID',
31
+ `channel("${declared.name}") declares no events, so nothing may listen for one on it`,
32
+ `declare it with events: true: channel('${declared.name}', { …, events: true })`,
33
+ );
34
+ const topic = declared.topic(params);
35
+ let open = true;
36
+ const sub = await channelTransport().subscribe(channelSubject(topic), (payload) => {
37
+ if (!open) return;
38
+ const frame = decode(payload);
39
+ if (frame.type === 'events' && frame.channel === topic) handler(frame.event);
40
+ });
41
+ const unsubscribe = (): void => {
42
+ if (!open) return;
43
+ open = false;
44
+ sub.unsubscribe();
45
+ };
46
+ return { unsubscribe, [Symbol.dispose]: unsubscribe };
47
+ }
48
+
49
+ export interface NextChannelEventOptions {
50
+ /**
51
+ * How long to wait once the listen is open — opening it is not counted. `0` or less (or `NaN`)
52
+ * answers `null` as soon as it is open, never an event that raced the open.
53
+ */
54
+ readonly timeoutMs: number;
55
+ /** Aborting rejects with the signal's `reason`, like any other abortable wait — even mid-open. */
56
+ readonly signal?: AbortSignal;
57
+ /** Only an event this accepts settles the wait — a feed carries other records' events too. */
58
+ readonly match?: (event: JsonObject) => boolean;
59
+ }
60
+
61
+ /**
62
+ * The next event on `declared`'s topic for `params` that `match` accepts, or `null` when
63
+ * `timeoutMs` passes first. The first outcome wins — an event, the deadline, an abort, a refused
64
+ * open, a `match` that throws — and the listen is closed however the wait ends, a listen that
65
+ * opens after it ended included. Read the state once more after it answers, either way: `null` is
66
+ * not "nothing happened" (delivery is at-most-once), and an event is "re-read", never the state.
67
+ */
68
+ export function nextChannelEvent<K extends string>(
69
+ declared: Channel<K>,
70
+ params: Readonly<Record<K, string>>,
71
+ options: NextChannelEventOptions,
72
+ ): Promise<JsonObject | null> {
73
+ const { signal, match, timeoutMs } = options;
74
+ return new Promise<JsonObject | null>((resolve, reject) => {
75
+ let done = false;
76
+ let sub: ChannelEventSubscription | undefined;
77
+ let timer: ReturnType<typeof setTimeout> | undefined;
78
+ const finish = (settle: () => void): void => {
79
+ if (done) return;
80
+ done = true;
81
+ clearTimeout(timer);
82
+ signal?.removeEventListener('abort', onAbort);
83
+ sub?.unsubscribe();
84
+ settle();
85
+ };
86
+ const onAbort = (): void => finish(() => reject(signal?.reason));
87
+ if (signal?.aborted) {
88
+ onAbort();
89
+ return;
90
+ }
91
+ signal?.addEventListener('abort', onAbort, { once: true });
92
+ const heard = (event: JsonObject): void => {
93
+ // A settled wait hears nothing more while its open finishes; a deadline of none answers
94
+ // null, so nothing heard while opening counts.
95
+ if (done || !(timeoutMs > 0)) return;
96
+ let accepted: boolean;
97
+ try {
98
+ accepted = match === undefined || match(event);
99
+ } catch (error) {
100
+ finish(() => reject(error));
101
+ return;
102
+ }
103
+ if (accepted) finish(() => resolve(event));
104
+ };
105
+ subscribeChannelEvents(declared, params, heard).then(
106
+ (opened) => {
107
+ if (done) {
108
+ opened.unsubscribe();
109
+ return;
110
+ }
111
+ sub = opened;
112
+ if (timeoutMs > 0) timer = setTimeout(() => finish(() => resolve(null)), timeoutMs);
113
+ else finish(() => resolve(null));
114
+ },
115
+ (error: unknown) => finish(() => reject(error)),
116
+ );
117
+ });
118
+ }
package/src/server.ts CHANGED
@@ -53,6 +53,13 @@ export { type ChannelDescription, describeChannels } from './channel-describe';
53
53
  // What a job or an action publishes an event with: the process's own bus, no hub needed.
54
54
  // Its installer is the boot's, on `./adapter` (`adapter.ts`), never here.
55
55
  export { publishChannelEvent } from './channel-publish';
56
+ // What server code waits on an event with — the same bus and subject, any process's publish.
57
+ export {
58
+ type ChannelEventSubscription,
59
+ type NextChannelEventOptions,
60
+ nextChannelEvent,
61
+ subscribeChannelEvents,
62
+ } from './channel-subscribe';
56
63
  // A resume's cursor as the node judged it; the signer itself is the registry's, never an export.
57
64
  export type { CursorDistrusted, CursorTrustOptions } from './cursor-sign';
58
65
  export {