@ultimat3/realtime 31.13.0 → 31.14.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.
@@ -14,9 +14,9 @@ import {
14
14
  import type { JsonValue } from './json';
15
15
  import { knownOffline, type OutboxHandle, peekOutbox } from './outbox-slot';
16
16
  import { OfflineQueueAbandonedError, ServerRenderLiveError } from './page-errors';
17
- import { installedPage, type PageWrites, pageRealtime } from './page-store';
17
+ import { enterLane, installedPage, type PageWrites, pageRealtime } from './page-store';
18
18
  import { mutationWire } from './pinned-wire';
19
- import { isServerRender, signalFor } from './reactivity';
19
+ import { isServerRender, ownedRelease, signalFor } from './reactivity';
20
20
  import { carriedBy } from './record-store';
21
21
 
22
22
  /**
@@ -42,7 +42,7 @@ export interface MutatorLike {
42
42
  export type Mutate = ((input: JsonValue) => Promise<unknown>) & {
43
43
  /** Calls of this mutator the server has not answered yet. */
44
44
  readonly pending: number;
45
- /** Stop counting for this hook (Solid: `onCleanup`). A call already made still settles. */
45
+ /** Stop counting for this hook; the component's cleanup does too. A call made still settles. */
46
46
  release(): void;
47
47
  [Symbol.dispose](): void;
48
48
  };
@@ -52,7 +52,7 @@ export interface MutationQueue extends Disposable {
52
52
  readonly pending: number;
53
53
  /** Writes the server refused since the page loaded. */
54
54
  readonly failed: number;
55
- /** Stop listening (Solid: `onCleanup`) — a page-wide listener outlives any one component. */
55
+ /** Stop listening; the component's cleanup does too — the page-wide counts outlive it. */
56
56
  release(): void;
57
57
  }
58
58
 
@@ -80,8 +80,9 @@ function count(writes: PageWrites, name: string, delta: number): void {
80
80
  function watch(hook: string, writes: PageWrites | undefined): [() => number, () => void] {
81
81
  const [version, setVersion] = signalFor(hook)(0);
82
82
  const listener = (): void => setVersion(version() + 1);
83
- writes?.listeners.add(listener);
84
- return [version, () => writes?.listeners.delete(listener)];
83
+ if (writes === undefined) return [version, () => undefined];
84
+ writes.listeners.add(listener);
85
+ return [version, ownedRelease(() => writes.listeners.delete(listener))];
85
86
  }
86
87
 
87
88
  /**
@@ -112,6 +113,27 @@ function restoreOverlays(mutator: MutatorLike): void {
112
113
  });
113
114
  }
114
115
 
116
+ /**
117
+ * How long a write waits for the previous write of its mutator before the outbox takes it over.
118
+ * Writes carry no client deadline (`clientFlight` never aborts one), so a POST on a half-open
119
+ * socket can hang for minutes; ten seconds is past any answer a live server gives, and short of
120
+ * the point a user gives up on the tap.
121
+ */
122
+ export const LANE_WAIT_MS = 10_000;
123
+
124
+ /** The lane's `ready`, or `'late'` once `LANE_WAIT_MS` passed first. The timer goes either way. */
125
+ async function laneTurn(ready: Promise<void>): Promise<'turn' | 'late'> {
126
+ let timer: ReturnType<typeof setTimeout> | undefined;
127
+ const late = new Promise<'late'>((resolve) => {
128
+ timer = setTimeout(() => resolve('late'), LANE_WAIT_MS);
129
+ });
130
+ try {
131
+ return await Promise.race([ready.then(() => 'turn' as const), late]);
132
+ } finally {
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+
115
137
  /** The page's outbox once the boot has finished opening it; `undefined` on a page with no boot. */
116
138
  async function bootedOutbox(page: {
117
139
  readonly booted: Promise<void>;
@@ -179,22 +201,10 @@ export function useMutation(mutator: MutatorLike): Mutate {
179
201
  throw error;
180
202
  }
181
203
  };
182
- // Asked of the DURABLE queue, re-read now: another tab of this user may have queued writes this
183
- // tab's copy has not heard of yet, and sending past them reorders the user's intent. Offline,
184
- // nothing is sent, so the question is moot and its read would only delay the disk write.
185
- if (queued !== undefined && !offline) {
186
- await queued.refresh().catch(() => undefined);
187
- // That read is an await: a principal that left meanwhile must not have this write POSTed, or
188
- // queued, as the next one. Refused by the code `enqueue` uses for the same departure.
189
- if (pageClient().scope.epoch !== issued) {
190
- page.store.drop(key);
191
- count(writes, mutator.name, -1);
192
- throw new OfflineQueueAbandonedError({ name: mutator.name });
193
- }
194
- }
195
- if (queued !== undefined && (offline || queued.pending().length > 0)) {
204
+ /** The write is the outbox's: queued under its key, behind what is already there, replayed. */
205
+ const viaOutbox = async (outbox: OutboxHandle): Promise<undefined> => {
196
206
  try {
197
- await enqueue(queued);
207
+ await enqueue(outbox);
198
208
  if (offline) {
199
209
  // Queued under the principal that made it; one that left since takes its page with it.
200
210
  if (pageClient().scope.epoch !== issued) {
@@ -202,63 +212,107 @@ export function useMutation(mutator: MutatorLike): Mutate {
202
212
  }
203
213
  paint();
204
214
  }
205
- void queued.replay().catch(() => undefined);
215
+ void outbox.replay().catch(() => undefined);
206
216
  return undefined;
207
217
  } finally {
208
218
  count(writes, mutator.name, -1);
209
219
  }
210
- }
211
- let output: unknown;
212
- /** The records the answer carried, `type:key` — what the overlay may be settled against. */
213
- const carried = new Set<string>();
220
+ };
221
+ // Offline, nothing is sent, so the lane below has nothing to order: the outbox's replay orders
222
+ // the queue. Joining it held the write off the disk behind a POST that may never answer (a
223
+ // half-open socket) — and a reload in that wait lost a write the user saw made (#777).
224
+ if (offline) return viaOutbox(queued);
225
+ // One lane per mutator NAME, page-wide: this write's network leg starts when the previous
226
+ // one of the same mutator settled — sent, queued or refused. Two online calls (like, then
227
+ // unlike) POSTed together could commit in either order, and the final row would contradict
228
+ // the last overlay the user saw. The overlay above is never held back: the screen is at once.
229
+ const lane = enterLane(writes, mutator.name);
214
230
  try {
215
- output = await page.services.send({
216
- method: wire.method,
217
- url: wire.url,
218
- body: wire.body,
219
- idempotencyKey: key,
220
- onEnvelope: (envelope) => carriedBy(envelope, carried),
221
- });
222
- } catch (error) {
223
- const failure = transportFailure(error);
224
- // No response at all — which is NOT "the write did not land": the POST may have committed
225
- // and lost its answer. The write is the outbox's now, under the SAME idempotency key, and
226
- // that replay is safe only because `mutator()` refuses a declaration without
227
- // `idempotent: true` (`X_MUTATOR_NOT_IDEMPOTENT`): the server reads the key and answers the
228
- // replay from its idempotency store, so the handler never runs twice. The overlay stays on
229
- // screen until the replay settles or refuses it. Only a page the boot opened
230
- // an outbox on can promise that; with none (no boot, so nothing on this page persists) the
231
- // write is refused like any other, never held in a memory queue a reload would silently lose.
232
- const outbox = failure === 'network' ? await bootedOutbox(page) : undefined;
233
- if (outbox !== undefined) {
234
- await enqueue(outbox);
235
- return undefined;
231
+ /** The lane's wait ran out: the write goes to the outbox, which orders whatever follows. */
232
+ let late = false;
233
+ // Only a write that found the lane busy awaits: an idle lane sends in this same tick.
234
+ if (lane.ready !== undefined) {
235
+ // Bounded only where a durable queue can take the write over; with none it waits its turn.
236
+ if (queued === undefined) await lane.ready;
237
+ else late = (await laneTurn(lane.ready)) === 'late';
238
+ // Waiting is an await: a principal that left meanwhile does not get this write sent as
239
+ // the next one — refused by the code the outbox path uses for the same departure.
240
+ if (pageClient().scope.epoch !== issued) {
241
+ page.store.drop(key);
242
+ count(writes, mutator.name, -1);
243
+ throw new OfflineQueueAbandonedError({ name: mutator.name });
244
+ }
236
245
  }
237
- if (failure === 'body') {
238
- // A 2xx whose body was not JSON: the write may well have landed, so it is neither queued
239
- // (a replay would be a second attempt) nor taken back — its overlay waits for the next
240
- // server row it touched. The caller is still told: nothing here can confirm it.
241
- page.store.awaitServer(key);
242
- writes.failed += 1;
246
+ // Asked of the DURABLE queue, re-read now: another tab of this user may have queued writes this
247
+ // tab's copy has not heard of yet, and sending past them reorders the user's intent.
248
+ if (queued !== undefined && !late) {
249
+ await queued.refresh().catch(() => undefined);
250
+ // That read is an await: a principal that left meanwhile must not have this write POSTed, or
251
+ // queued, as the next one. Refused by the code `enqueue` uses for the same departure.
252
+ if (pageClient().scope.epoch !== issued) {
253
+ page.store.drop(key);
254
+ count(writes, mutator.name, -1);
255
+ throw new OfflineQueueAbandonedError({ name: mutator.name });
256
+ }
257
+ }
258
+ // Awaited, not returned: the lane opens for the next write only once this one is on disk.
259
+ if (queued !== undefined && (late || queued.pending().length > 0)) {
260
+ return await viaOutbox(queued);
261
+ }
262
+ let output: unknown;
263
+ /** The records the answer carried, `type:key` — what the overlay may be settled against. */
264
+ const carried = new Set<string>();
265
+ try {
266
+ output = await page.services.send({
267
+ method: wire.method,
268
+ url: wire.url,
269
+ body: wire.body,
270
+ idempotencyKey: key,
271
+ onEnvelope: (envelope) => carriedBy(envelope, carried),
272
+ });
273
+ } catch (error) {
274
+ const failure = transportFailure(error);
275
+ // No response at all — which is NOT "the write did not land": the POST may have committed
276
+ // and lost its answer. The write is the outbox's now, under the SAME idempotency key, and
277
+ // that replay is safe only because `mutator()` refuses a declaration without
278
+ // `idempotent: true` (`X_MUTATOR_NOT_IDEMPOTENT`): the server reads the key and answers the
279
+ // replay from its idempotency store, so the handler never runs twice. The overlay stays on
280
+ // screen until the replay settles or refuses it. Only a page the boot opened
281
+ // an outbox on can promise that; with none (no boot, so nothing on this page persists) the
282
+ // write is refused like any other, never held in a memory queue a reload would silently lose.
283
+ const outbox = failure === 'network' ? await bootedOutbox(page) : undefined;
284
+ if (outbox !== undefined) {
285
+ await enqueue(outbox);
286
+ return undefined;
287
+ }
288
+ if (failure === 'body') {
289
+ // A 2xx whose body was not JSON: the write may well have landed, so it is neither queued
290
+ // (a replay would be a second attempt) nor taken back — its overlay waits for the next
291
+ // server row it touched. The caller is still told: nothing here can confirm it.
292
+ page.store.awaitServer(key);
293
+ writes.failed += 1;
294
+ throw error;
295
+ }
296
+ page.store.drop(key);
297
+ // A write superseded by a principal change DID land; it is the previous principal's, and
298
+ // nothing about it is this page's failure to report.
299
+ if (!isSuperseded(error)) writes.failed += 1;
243
300
  throw error;
301
+ } finally {
302
+ count(writes, mutator.name, -1);
244
303
  }
245
- page.store.drop(key);
246
- // A write superseded by a principal change DID land; it is the previous principal's, and
247
- // nothing about it is this page's failure to report.
248
- if (!isSuperseded(error)) writes.failed += 1;
249
- throw error;
304
+ try {
305
+ // A row the answer did not carry keeps its overlay until the server's row reaches it.
306
+ page.store.settle(key, carried);
307
+ } catch (error) {
308
+ // A custom merge that answered no row: the server's truth stands, and the caller is told.
309
+ page.store.drop(key);
310
+ throw error;
311
+ }
312
+ return output;
250
313
  } finally {
251
- count(writes, mutator.name, -1);
252
- }
253
- try {
254
- // A row the answer did not carry keeps its overlay until the server's row reaches it.
255
- page.store.settle(key, carried);
256
- } catch (error) {
257
- // A custom merge that answered no row: the server's truth stands, and the caller is told.
258
- page.store.drop(key);
259
- throw error;
314
+ lane.leave();
260
315
  }
261
- return output;
262
316
  };
263
317
  Object.defineProperty(call, 'pending', {
264
318
  get: (): number => {
package/src/use-outbox.ts CHANGED
@@ -4,10 +4,10 @@
4
4
 
5
5
  import { peekOutbox } from './outbox-slot';
6
6
  import { installedPage } from './page-store';
7
- import { isServerRender, signalFor } from './reactivity';
7
+ import { isServerRender, ownedRelease, signalFor } from './reactivity';
8
8
 
9
9
  export interface OutboxView extends Disposable {
10
- /** Stop listening (Solid: `onCleanup`). The outbox itself stays, and keeps its writes. */
10
+ /** Stop listening — the component's cleanup does it too. The outbox stays, with its writes. */
11
11
  release(): void;
12
12
  /** Writes queued and not yet taken by the server; `0` before the boot has opened the outbox. */
13
13
  readonly size: number;
@@ -34,10 +34,10 @@ export function useOutbox(): OutboxView {
34
34
  unsubscribe = outbox.subscribe(moved);
35
35
  moved();
36
36
  });
37
- const release = (): void => {
37
+ const release = ownedRelease(() => {
38
38
  released = true;
39
39
  unsubscribe();
40
- };
40
+ });
41
41
  return {
42
42
  release,
43
43
  [Symbol.dispose]: release,
package/src/use-query.ts CHANGED
@@ -8,7 +8,7 @@ import type { LiveHandle } from './client-contract';
8
8
  import type { JsonValue } from './json';
9
9
  import { installedPage, type PageServices } from './page-store';
10
10
  import type { QueryPoll } from './query-poll';
11
- import { isServerRender, signalFor } from './reactivity';
11
+ import { isServerRender, ownedRelease, signalFor } from './reactivity';
12
12
  import { keptAnswer } from './record-answer';
13
13
  import { type RecordStore, recordKey } from './record-store';
14
14
 
@@ -148,11 +148,11 @@ function liveAccessor<R extends object>(
148
148
  waiting.length > 0 || (handle.state() === 'failed' && handle.retry())
149
149
  ? new Promise((resolve) => waiting.push(resolve))
150
150
  : settled();
151
- const release = (): void => {
151
+ const release = ownedRelease(() => {
152
152
  off();
153
153
  settle();
154
154
  handle.unsubscribe();
155
- };
155
+ });
156
156
  return Object.assign(read, {
157
157
  refetch,
158
158
  more: nothing,
@@ -301,14 +301,13 @@ function readAccessor<R extends object>(
301
301
  if (state.status === 'failed') throw state.error;
302
302
  }),
303
303
  );
304
- const release = (): void => {
305
- if (released) return;
304
+ const release = ownedRelease(() => {
306
305
  released = true;
307
306
  stopPoll?.();
308
307
  off();
309
308
  hold([]);
310
309
  keys = [];
311
- };
310
+ });
312
311
  return Object.assign(read, {
313
312
  refetch,
314
313
  more: () => {
@@ -4,12 +4,12 @@
4
4
  // a server page, flash a counter — pays nothing here: it holds no row and no type.
5
5
 
6
6
  import { pageStore } from './page-store';
7
- import { isServerRender } from './reactivity';
7
+ import { isServerRender, ownedRelease } from './reactivity';
8
8
 
9
9
  /** Per type, the keys of its records that one store update moved (written, removed or evicted). */
10
10
  export type RecordChanges = ReadonlyMap<string, readonly string[]>;
11
11
 
12
- /** The listener's undo — call it, `release()` it or `using` it (Solid: `onCleanup`). */
12
+ /** The listener's undo — call it, `release()` it or `using` it; the component's cleanup does too. */
13
13
  export type RecordChangesHandle = (() => void) & { release(): void; [Symbol.dispose](): void };
14
14
 
15
15
  const nothing = (): void => undefined;
@@ -37,11 +37,6 @@ export function useRecordChanges(
37
37
  }
38
38
  if (moved.size > 0) listener(moved);
39
39
  });
40
- let held = true;
41
- const release = (): void => {
42
- if (!held) return;
43
- held = false;
44
- unsubscribe();
45
- };
40
+ const release = ownedRelease(unsubscribe);
46
41
  return Object.assign(release, { release, [Symbol.dispose]: release });
47
42
  }
package/src/use-record.ts CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  import type { AsyncState, Row } from '@ultimat3/core/page';
7
7
  import { pageStore } from './page-store';
8
- import { isServerRender, signalFor } from './reactivity';
8
+ import { isServerRender, ownedRelease, signalFor } from './reactivity';
9
9
  import { keptAnswer, throttledNotify } from './record-answer';
10
10
  import { type RecordKey, type RecordStore, recordKey } from './record-store';
11
11
  import type { Scheduler } from './thundering-herd';
@@ -13,7 +13,7 @@ import type { Scheduler } from './thundering-herd';
13
13
  /**
14
14
  * A callable `AsyncState`: `pending` until the record first arrives, `ready` from then on —
15
15
  * `ready` with `undefined` once the server removed it, so a deleted record is a settled answer
16
- * and never a skeleton forever. `release()` lets go; the caller owns it (Solid: `onCleanup`).
16
+ * and never a skeleton forever. `release()` lets go; the component's cleanup calls it on its own.
17
17
  */
18
18
  export type RecordAccessor<R extends object = Row> = (() => AsyncState<R | undefined>) & {
19
19
  release(): void;
@@ -56,13 +56,10 @@ export function useRecord<R extends object = Row>(type: string, key: string): Re
56
56
  if (answer.status !== 'ready' || answer.data !== row) answer = { status: 'ready', data: row };
57
57
  return answer;
58
58
  };
59
- let held = true;
60
- const release = (): void => {
61
- if (!held) return;
62
- held = false;
59
+ const release = ownedRelease(() => {
63
60
  unsubscribe();
64
61
  store.release(type, key);
65
- };
62
+ });
66
63
  return Object.assign(read, { release, [Symbol.dispose]: release });
67
64
  }
68
65
 
@@ -162,15 +159,12 @@ function byKeys<R extends object>(
162
159
  answer = keptAnswer(answer, 'ready', rows);
163
160
  return answer;
164
161
  };
165
- let held = true;
166
- const release = (): void => {
167
- if (!held) return;
168
- held = false;
162
+ const release = ownedRelease(() => {
169
163
  unsubscribe();
170
164
  store.batch(() => {
171
165
  for (const key of keys) store.release(type, key);
172
166
  });
173
- };
167
+ });
174
168
  return Object.assign(read, { release, [Symbol.dispose]: release });
175
169
  }
176
170
 
@@ -234,13 +228,10 @@ function ofType<R extends object>(
234
228
  answered = at;
235
229
  return answer;
236
230
  };
237
- let held = true;
238
- const release = (): void => {
239
- if (!held) return;
240
- held = false;
231
+ const release = ownedRelease(() => {
241
232
  notify.cancel();
242
233
  unsubscribe();
243
234
  store.releaseType(type);
244
- };
235
+ });
245
236
  return Object.assign(read, { release, [Symbol.dispose]: release });
246
237
  }