@hadoku/room-ask 0.0.0-stage → 0.1.8

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hadoku-cardtable contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,40 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ */
8
+ /** A scheduled callback that can be called off. Cancelling twice is a no-op. */
9
+ export interface AskTimer {
10
+ cancel(): void;
11
+ }
12
+ /**
13
+ * The registry's entire relationship with time. Both halves are injected
14
+ * together because a deadline needs the two to agree: `now()` decides what
15
+ * `issuedAt`/`deadlineAt` say, `setTimer` decides when the ask actually fires.
16
+ * Splitting them is how a test ends up with a clock at t=5000 and a timer that
17
+ * has not run.
18
+ */
19
+ export interface AskClock {
20
+ /** Epoch ms. */
21
+ now(): number;
22
+ /** Fire `fn` once, `delayMs` from now. */
23
+ setTimer(delayMs: number, fn: () => void): AskTimer;
24
+ }
25
+ /** `Date.now` + `setTimeout`. The default, and the only thing that touches the host runtime. */
26
+ export declare function createSystemClock(): AskClock;
27
+ export interface ManualClock extends AskClock {
28
+ /**
29
+ * Move time forward, firing every timer that comes due, each one observing
30
+ * `now()` equal to its own deadline rather than the end of the window.
31
+ * Timers armed from inside a callback are picked up in the same sweep if
32
+ * they fall before `target`.
33
+ */
34
+ advance(ms: number): void;
35
+ }
36
+ /**
37
+ * A clock tests drive by hand. Deterministic and sleep-free: nothing here ever
38
+ * consults the real time or yields to the event loop.
39
+ */
40
+ export declare function createManualClock(start?: number): ManualClock;
package/dist/clock.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ */
8
+ /** `Date.now` + `setTimeout`. The default, and the only thing that touches the host runtime. */
9
+ export function createSystemClock() {
10
+ return {
11
+ now: () => Date.now(),
12
+ setTimer(delayMs, fn) {
13
+ const handle = setTimeout(fn, Math.max(0, delayMs));
14
+ // Node-only: an ask's deadline must not hold the process open by itself.
15
+ handle.unref?.();
16
+ return {
17
+ cancel() {
18
+ clearTimeout(handle);
19
+ },
20
+ };
21
+ },
22
+ };
23
+ }
24
+ /**
25
+ * A clock tests drive by hand. Deterministic and sleep-free: nothing here ever
26
+ * consults the real time or yields to the event loop.
27
+ */
28
+ export function createManualClock(start = 0) {
29
+ let current = start;
30
+ let nextSeq = 0;
31
+ const timers = new Map();
32
+ return {
33
+ now: () => current,
34
+ setTimer(delayMs, fn) {
35
+ const seq = nextSeq++;
36
+ timers.set(seq, { seq, dueAt: current + Math.max(0, delayMs), fn });
37
+ return {
38
+ cancel() {
39
+ timers.delete(seq);
40
+ },
41
+ };
42
+ },
43
+ advance(ms) {
44
+ const target = current + Math.max(0, ms);
45
+ for (;;) {
46
+ let next = null;
47
+ for (const timer of timers.values()) {
48
+ if (timer.dueAt > target)
49
+ continue;
50
+ // Ties break on arm order, so a deterministic sequence stays one.
51
+ if (next === null || timer.dueAt < next.dueAt || (timer.dueAt === next.dueAt && timer.seq < next.seq)) {
52
+ next = timer;
53
+ }
54
+ }
55
+ if (next === null)
56
+ break;
57
+ timers.delete(next.seq);
58
+ current = Math.max(current, next.dueAt);
59
+ next.fn();
60
+ }
61
+ current = target;
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ */
8
+ import type { ParticipantId, SeatId } from '@wolffm/rooms-protocol';
9
+ import type { AskCancelReason, AskId } from './types.js';
10
+ /** Thrown into the caller's promise only when `onTimeout.mode === 'throw'`. */
11
+ export declare class AskTimeoutError extends Error {
12
+ readonly askId: AskId;
13
+ readonly timeoutMs: number;
14
+ constructor(askId: AskId, timeoutMs: number);
15
+ }
16
+ /**
17
+ * Cancellation ALWAYS rejects. There is no cancel-with-value mode, by symmetry
18
+ * with the fact that a cancelled question has no answer to stand in for.
19
+ */
20
+ export declare class AskCancelledError extends Error {
21
+ readonly askId: AskId;
22
+ readonly reason: AskCancelReason;
23
+ constructor(askId: AskId, reason: AskCancelReason);
24
+ }
25
+ /**
26
+ * The target holds no seat — or names a seat that is empty, out of range, or
27
+ * occupied by a bot. Rejected at issue: no `askId` is allocated, no counter
28
+ * moves, and in particular `droppedUnknownReplies` is untouched.
29
+ */
30
+ export declare class AskNotSeatedError extends Error {
31
+ readonly target: ParticipantId | SeatId;
32
+ constructor(target: ParticipantId | SeatId);
33
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ */
8
+ /** Thrown into the caller's promise only when `onTimeout.mode === 'throw'`. */
9
+ export class AskTimeoutError extends Error {
10
+ askId;
11
+ timeoutMs;
12
+ constructor(askId, timeoutMs) {
13
+ super(`ask ${askId} timed out after ${timeoutMs}ms`);
14
+ this.name = 'AskTimeoutError';
15
+ this.askId = askId;
16
+ this.timeoutMs = timeoutMs;
17
+ }
18
+ }
19
+ /**
20
+ * Cancellation ALWAYS rejects. There is no cancel-with-value mode, by symmetry
21
+ * with the fact that a cancelled question has no answer to stand in for.
22
+ */
23
+ export class AskCancelledError extends Error {
24
+ askId;
25
+ reason;
26
+ constructor(askId, reason) {
27
+ super(`ask ${askId} cancelled (${reason})`);
28
+ this.name = 'AskCancelledError';
29
+ this.askId = askId;
30
+ this.reason = reason;
31
+ }
32
+ }
33
+ /**
34
+ * The target holds no seat — or names a seat that is empty, out of range, or
35
+ * occupied by a bot. Rejected at issue: no `askId` is allocated, no counter
36
+ * moves, and in particular `droppedUnknownReplies` is untouched.
37
+ */
38
+ export class AskNotSeatedError extends Error {
39
+ target;
40
+ constructor(target) {
41
+ super(`ask target ${String(target)} is not a seated participant`);
42
+ this.name = 'AskNotSeatedError';
43
+ this.target = target;
44
+ }
45
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * `@hadoku/room-ask` — a durable, seat-scoped request/response over a room.
5
+ *
6
+ * MIT: the single carve-out in a repo that is otherwise GPL-3.0-or-later.
7
+ * Written clean-room from the requirement in `docs/requests/P4_ASK_REGISTRY.md`
8
+ * and from nothing else. See `packages/room-ask/LICENSE`.
9
+ */
10
+ export { createAskRegistry, type AskRegistry, type AskRegistryOptions } from './registry.js';
11
+ export { AskCancelledError, AskNotSeatedError, AskTimeoutError } from './errors.js';
12
+ export { createManualClock, createSystemClock, type AskClock, type AskTimer, type ManualClock, } from './clock.js';
13
+ export type { AskCancelReason, AskDeliverFn, AskEnvelope, AskId, AskOptions, AskReply, AskState, AskStats, AskTimeoutPolicy, PendingAskView, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * `@hadoku/room-ask` — a durable, seat-scoped request/response over a room.
5
+ *
6
+ * MIT: the single carve-out in a repo that is otherwise GPL-3.0-or-later.
7
+ * Written clean-room from the requirement in `docs/requests/P4_ASK_REGISTRY.md`
8
+ * and from nothing else. See `packages/room-ask/LICENSE`.
9
+ */
10
+ export { createAskRegistry } from "./registry.js";
11
+ export { AskCancelledError, AskNotSeatedError, AskTimeoutError } from "./errors.js";
12
+ export { createManualClock, createSystemClock, } from "./clock.js";
@@ -0,0 +1,137 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ *
8
+ * ## What this is
9
+ *
10
+ * A server-side caller puts a question to ONE seated participant and awaits the
11
+ * answer while the rest of the room keeps running. "Pick a card." "Mulligan?"
12
+ *
13
+ * The one idea underneath every rule here: **participants and seats are
14
+ * durable, sockets are not.** Every ask is keyed to the durable things, so a
15
+ * mid-draft browser refresh moves an ask from `delivered` back to `queued` and
16
+ * settles nothing at all.
17
+ *
18
+ * ## What it deliberately does not do
19
+ *
20
+ * It opens nothing, imports no transport, and reads no clock it was not handed.
21
+ * Sockets reach it only as opaque string keys through {@link AskRegistry.attach}
22
+ * and {@link AskRegistry.detach}; envelopes leave through a delivery callback.
23
+ * That is what makes requirement 8 — "an unknown id is dropped and counted,
24
+ * never thrown" — testable without a live socket.
25
+ */
26
+ import { type ParticipantId, type SeatId, type SeatTable } from '@wolffm/rooms-protocol';
27
+ import { type AskClock } from './clock.js';
28
+ import type { AskCancelReason, AskDeliverFn, AskId, AskOptions, AskReply, AskStats, PendingAskView } from './types.js';
29
+ export interface AskRegistryOptions {
30
+ /**
31
+ * The room's live seat table. Held by reference and read at issue time only —
32
+ * the registry never mutates it and never polls it. A seat losing its
33
+ * occupant reaches the registry through {@link AskRegistry.seatExit}, not
34
+ * through this table changing under it.
35
+ */
36
+ seats: SeatTable;
37
+ /** How an envelope reaches one socket. */
38
+ deliver: AskDeliverFn;
39
+ /** Defaults to `Date.now` + `setTimeout`. Tests pass a manual clock. */
40
+ clock?: AskClock;
41
+ }
42
+ export interface AskRegistry {
43
+ /**
44
+ * Put a question to one seated participant.
45
+ *
46
+ * Target resolution happens ONCE, here. A {@link SeatId} resolves to whoever
47
+ * occupies that seat at this instant and the ask is then bound to that
48
+ * *participant* for its whole life — if the occupant changes, the ask is
49
+ * cancelled (`reason: 'seat-exit'`) rather than silently handed to the new
50
+ * occupant. One player's hidden-state question never reaches another player.
51
+ *
52
+ * Rejects at issue with {@link AskNotSeatedError} when the target holds no
53
+ * seat, or names a seat that is empty, out of range, or occupied by a bot
54
+ * (see the §6.8 note on {@link AskRegistry.seatExit}'s sibling decision). No
55
+ * `askId` is allocated and no counter moves.
56
+ *
57
+ * `timeoutMs` is wall-clock from here and does NOT pause while queued: a
58
+ * draft's pick timer means what it says.
59
+ */
60
+ ask<T>(target: ParticipantId | SeatId, kind: string, payload: unknown, opts: AskOptions<T>): Promise<T>;
61
+ /** Snapshot of everything not yet settled, in ascending `askId` order. */
62
+ pending(): ReadonlyArray<PendingAskView>;
63
+ /** Monotonic counters plus the `queued` gauge. Never reset. */
64
+ stats(): AskStats;
65
+ /**
66
+ * Cancel one pending ask. `true` if it was pending and is now cancelled,
67
+ * `false` if it had already settled or never existed. Safe to call repeatedly.
68
+ */
69
+ cancel(askId: AskId, reason?: AskCancelReason): boolean;
70
+ /**
71
+ * A socket became live for this participant.
72
+ *
73
+ * Every still-pending ask for them is (re-)written to the new socket in
74
+ * ascending `askId` order, unchanged: same `askId`, the same frozen envelope
75
+ * object, no new deadline. Replaying n times and replaying once are
76
+ * indistinguishable to the caller — only the `delivered` emit counter moves.
77
+ *
78
+ * `socketKey` is opaque; the registry only ever compares it for equality and
79
+ * hands it back to `deliver`. Attaching a key that is already attached does
80
+ * nothing at all.
81
+ *
82
+ * Replay is for durable participants. An `eph:` id IS the socket id, so "the
83
+ * same participant attaches a second socket" is not a thing that can happen
84
+ * to one — their first attach delivers normally, and if that socket goes away
85
+ * their queued asks can only time out. `isDurableParticipantId` is the gate.
86
+ */
87
+ attach(participantId: ParticipantId, socketKey: string): void;
88
+ /**
89
+ * A socket went away. If it was the participant's last one, their `delivered`
90
+ * asks move back to `queued` and NOTHING settles. This is the only effect a
91
+ * socket drop has anywhere in this module.
92
+ */
93
+ detach(participantId: ParticipantId, socketKey: string): void;
94
+ /**
95
+ * The participant genuinely left their seat: every pending ask for them is
96
+ * cancelled with `reason: 'seat-exit'`.
97
+ *
98
+ * ## The contract, which is the whole of requirement 7
99
+ *
100
+ * **The host decides what "left the seat" means, and it must NOT mean "a
101
+ * socket dropped".** A mid-draft refresh drops a socket and leaves a stale
102
+ * disconnect behind while the participant is already back on a new one; if
103
+ * that path calls `seatExit`, it cancels every pending ask for a drafter who
104
+ * never went anywhere — precisely the outcome requirement 7 exists to forbid,
105
+ * arriving through the door we thought we had closed.
106
+ *
107
+ * So: call {@link AskRegistry.detach} on a disconnect, and call this only on a
108
+ * deliberate departure — leaving the pod, being removed from a seat, a seat's
109
+ * occupant being swapped. The registry cannot tell the two apart and does not
110
+ * try; that judgement is the caller's, and it is the caller's whole job here.
111
+ *
112
+ * Idempotent: running the sweep twice cancels the same set once.
113
+ */
114
+ seatExit(participantId: ParticipantId): void;
115
+ /**
116
+ * The room is over. Every pending ask is cancelled with
117
+ * `reason: 'room-closed'` and the socket registry is emptied.
118
+ *
119
+ * Asks issued after this point are accepted, counted and immediately
120
+ * cancelled the same way — the counters stay consistent, but a host that
121
+ * relies on it is asking a question of a room that no longer exists.
122
+ */
123
+ closeRoom(): void;
124
+ /**
125
+ * Ingress for the transport adapter, and the seam that makes requirement 8
126
+ * testable without a socket. NEVER throws.
127
+ *
128
+ * `'matched'` only when the `askId` is pending here AND `from` is that ask's
129
+ * resolved target participant. Everything else — an id that never existed,
130
+ * one that already settled, a second reply to the same id, a valid id from
131
+ * the wrong participant, an id from a previous room — is discarded, bumps
132
+ * `droppedUnknownReplies` by exactly one, and returns `'dropped'`. No throw
133
+ * reaches the transport handler and no caller's promise is disturbed.
134
+ */
135
+ submitReply(from: ParticipantId, reply: AskReply): 'matched' | 'dropped';
136
+ }
137
+ export declare function createAskRegistry(opts: AskRegistryOptions): AskRegistry;
@@ -0,0 +1,253 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ *
8
+ * ## What this is
9
+ *
10
+ * A server-side caller puts a question to ONE seated participant and awaits the
11
+ * answer while the rest of the room keeps running. "Pick a card." "Mulligan?"
12
+ *
13
+ * The one idea underneath every rule here: **participants and seats are
14
+ * durable, sockets are not.** Every ask is keyed to the durable things, so a
15
+ * mid-draft browser refresh moves an ask from `delivered` back to `queued` and
16
+ * settles nothing at all.
17
+ *
18
+ * ## What it deliberately does not do
19
+ *
20
+ * It opens nothing, imports no transport, and reads no clock it was not handed.
21
+ * Sockets reach it only as opaque string keys through {@link AskRegistry.attach}
22
+ * and {@link AskRegistry.detach}; envelopes leave through a delivery callback.
23
+ * That is what makes requirement 8 — "an unknown id is dropped and counted,
24
+ * never thrown" — testable without a live socket.
25
+ */
26
+ import { occupantOf, seatOf, isDurableParticipantId, } from '@wolffm/rooms-protocol';
27
+ import { createSystemClock } from "./clock.js";
28
+ import { AskCancelledError, AskNotSeatedError, AskTimeoutError } from "./errors.js";
29
+ const EMPTY_SOCKETS = new Set();
30
+ export function createAskRegistry(opts) {
31
+ const { seats, deliver } = opts;
32
+ const clock = opts.clock ?? createSystemClock();
33
+ /** Strictly increasing, +1 each time, never reused, never reset. */
34
+ let nextAskId = 1;
35
+ const asks = new Map();
36
+ const sockets = new Map();
37
+ /** Participants that have held a socket at some point — the re-attach test. */
38
+ const everAttached = new Set();
39
+ let roomClosed = false;
40
+ const counters = {
41
+ issued: 0,
42
+ delivered: 0,
43
+ replied: 0,
44
+ timedOut: 0,
45
+ cancelled: 0,
46
+ droppedUnknownReplies: 0,
47
+ };
48
+ function socketsOf(participantId) {
49
+ return sockets.get(participantId) ?? EMPTY_SOCKETS;
50
+ }
51
+ /** Pending asks for one participant, ascending `askId`. */
52
+ function pendingFor(participantId) {
53
+ const out = [];
54
+ for (const record of asks.values()) {
55
+ if (record.target === participantId)
56
+ out.push(record);
57
+ }
58
+ out.sort((a, b) => a.askId - b.askId);
59
+ return out;
60
+ }
61
+ function emitTo(record, socketKey) {
62
+ record.emitCount += 1;
63
+ counters.delivered += 1;
64
+ deliver(record.target, socketKey, record.envelope);
65
+ }
66
+ function finish(record, outcome) {
67
+ // Terminal is terminal: a late reply, a late timer, a late abort or a late
68
+ // seat-exit against an ask that has already gone changes nothing. The map
69
+ // delete below is what makes every one of those a lookup miss.
70
+ if (!asks.delete(record.askId))
71
+ return;
72
+ record.timer?.cancel();
73
+ record.timer = null;
74
+ record.detachAbort?.();
75
+ record.detachAbort = null;
76
+ record.settle(outcome);
77
+ }
78
+ function resolveTarget(target) {
79
+ if (typeof target === 'number') {
80
+ const occupant = occupantOf(seats, target);
81
+ // A bot has no socket and never will, so queueing an ask for one is a
82
+ // guaranteed timeout dressed up as a pending request. Same answer as an
83
+ // empty seat: refuse at issue.
84
+ if (occupant === null || occupant.kind !== 'human')
85
+ return null;
86
+ return { participantId: occupant.participantId, seat: target };
87
+ }
88
+ const seat = seatOf(seats, target);
89
+ if (seat === null)
90
+ return null;
91
+ return { participantId: target, seat };
92
+ }
93
+ function ask(target, kind, payload, options) {
94
+ const resolved = resolveTarget(target);
95
+ if (resolved === null)
96
+ return Promise.reject(new AskNotSeatedError(target));
97
+ const askId = nextAskId;
98
+ nextAskId += 1;
99
+ const issuedAt = clock.now();
100
+ const timeoutMs = options.timeoutMs;
101
+ const envelope = Object.freeze({ askId, kind, payload });
102
+ let resolveOuter;
103
+ let rejectOuter;
104
+ const promise = new Promise((res, rej) => {
105
+ resolveOuter = res;
106
+ rejectOuter = rej;
107
+ });
108
+ const record = {
109
+ askId,
110
+ kind,
111
+ target: resolved.participantId,
112
+ seat: resolved.seat,
113
+ envelope,
114
+ issuedAt,
115
+ deadlineAt: issuedAt + timeoutMs,
116
+ timeoutMs,
117
+ state: 'queued',
118
+ emitCount: 0,
119
+ timer: null,
120
+ detachAbort: null,
121
+ settle(outcome) {
122
+ switch (outcome.kind) {
123
+ case 'replied':
124
+ counters.replied += 1;
125
+ resolveOuter(outcome.value);
126
+ return;
127
+ case 'timedOut':
128
+ counters.timedOut += 1;
129
+ if (options.onTimeout.mode === 'value')
130
+ resolveOuter(options.onTimeout.value);
131
+ else
132
+ rejectOuter(new AskTimeoutError(askId, timeoutMs));
133
+ return;
134
+ case 'cancelled':
135
+ counters.cancelled += 1;
136
+ rejectOuter(new AskCancelledError(askId, outcome.reason));
137
+ return;
138
+ }
139
+ },
140
+ };
141
+ asks.set(askId, record);
142
+ counters.issued += 1;
143
+ record.timer = clock.setTimer(timeoutMs, () => {
144
+ finish(record, { kind: 'timedOut' });
145
+ });
146
+ const signal = options.signal;
147
+ if (signal) {
148
+ const onAbort = () => finish(record, { kind: 'cancelled', reason: 'signal' });
149
+ if (signal.aborted) {
150
+ onAbort();
151
+ return promise;
152
+ }
153
+ signal.addEventListener('abort', onAbort, { once: true });
154
+ record.detachAbort = () => signal.removeEventListener('abort', onAbort);
155
+ }
156
+ if (roomClosed) {
157
+ finish(record, { kind: 'cancelled', reason: 'room-closed' });
158
+ return promise;
159
+ }
160
+ // T1 / T2, same tick either way: deliver to every live socket, or queue.
161
+ const live = socketsOf(record.target);
162
+ if (live.size > 0) {
163
+ record.state = 'delivered';
164
+ for (const socketKey of live)
165
+ emitTo(record, socketKey);
166
+ }
167
+ return promise;
168
+ }
169
+ function cancel(askId, reason = 'cancelled') {
170
+ const record = asks.get(askId);
171
+ if (!record)
172
+ return false;
173
+ finish(record, { kind: 'cancelled', reason });
174
+ return true;
175
+ }
176
+ function attach(participantId, socketKey) {
177
+ let live = sockets.get(participantId);
178
+ if (!live) {
179
+ live = new Set();
180
+ sockets.set(participantId, live);
181
+ }
182
+ if (live.has(socketKey))
183
+ return; // idempotent: already present, nothing moves
184
+ const isReattach = everAttached.has(participantId);
185
+ live.add(socketKey);
186
+ everAttached.add(participantId);
187
+ // An ephemeral participant cannot come back — their id is the socket that
188
+ // just died — so a second attach under that id is a host mistake, not a
189
+ // reconnect, and replaying someone's hidden-state question onto it would be
190
+ // worse than letting the ask time out.
191
+ if (isReattach && !isDurableParticipantId(participantId))
192
+ return;
193
+ for (const record of pendingFor(participantId)) {
194
+ record.state = 'delivered'; // T4 from queued, T5 self-loop from delivered
195
+ emitTo(record, socketKey);
196
+ }
197
+ }
198
+ function detach(participantId, socketKey) {
199
+ const live = sockets.get(participantId);
200
+ if (!live || !live.delete(socketKey))
201
+ return; // not attached: nothing moves
202
+ if (live.size > 0)
203
+ return;
204
+ sockets.delete(participantId);
205
+ // T3, and T3 is the ONLY thing a socket drop does. Nothing settles.
206
+ for (const record of pendingFor(participantId))
207
+ record.state = 'queued';
208
+ }
209
+ function seatExit(participantId) {
210
+ for (const record of pendingFor(participantId)) {
211
+ finish(record, { kind: 'cancelled', reason: 'seat-exit' });
212
+ }
213
+ }
214
+ function closeRoom() {
215
+ roomClosed = true;
216
+ for (const record of [...asks.values()].sort((a, b) => a.askId - b.askId)) {
217
+ finish(record, { kind: 'cancelled', reason: 'room-closed' });
218
+ }
219
+ sockets.clear();
220
+ }
221
+ function submitReply(from, reply) {
222
+ const record = asks.get(reply?.askId);
223
+ // Both halves of §2.5's match rule, and the only place either is decided.
224
+ if (!record || record.target !== from) {
225
+ counters.droppedUnknownReplies += 1;
226
+ return 'dropped';
227
+ }
228
+ finish(record, { kind: 'replied', value: reply.value });
229
+ return 'matched';
230
+ }
231
+ function pending() {
232
+ return [...asks.values()]
233
+ .sort((a, b) => a.askId - b.askId)
234
+ .map((record) => ({
235
+ askId: record.askId,
236
+ kind: record.kind,
237
+ target: record.target,
238
+ seat: record.seat,
239
+ state: record.state,
240
+ issuedAt: record.issuedAt,
241
+ deadlineAt: record.deadlineAt,
242
+ emitCount: record.emitCount,
243
+ }));
244
+ }
245
+ function stats() {
246
+ let queued = 0;
247
+ for (const record of asks.values())
248
+ if (record.state === 'queued')
249
+ queued += 1;
250
+ return { ...counters, queued };
251
+ }
252
+ return { ask, pending, stats, cancel, attach, detach, seatExit, closeRoom, submitReply };
253
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ */
8
+ import type { ParticipantId, SeatId } from '@wolffm/rooms-protocol';
9
+ /**
10
+ * Correlation id. Allocated from a per-registry counter starting at 1 and
11
+ * incrementing by exactly 1 — strictly increasing over the registry's life,
12
+ * never reused, never reset by a reconnect. Branded so an arbitrary number
13
+ * cannot be passed where a real id is expected.
14
+ */
15
+ export type AskId = number & {
16
+ readonly __brand: 'AskId';
17
+ };
18
+ /** server → the target participant's sockets. `askId` is the only join key. */
19
+ export interface AskEnvelope {
20
+ readonly askId: AskId;
21
+ readonly kind: string;
22
+ readonly payload: unknown;
23
+ }
24
+ /** any of that participant's sockets → server. */
25
+ export interface AskReply {
26
+ readonly askId: AskId;
27
+ readonly value: unknown;
28
+ }
29
+ /**
30
+ * What a timeout does. There is no implicit default: `value` resolves the
31
+ * caller's promise with exactly the value they supplied up front, `throw`
32
+ * rejects it with an {@link AskTimeoutError}.
33
+ */
34
+ export type AskTimeoutPolicy<T> = {
35
+ mode: 'value';
36
+ value: T;
37
+ } | {
38
+ mode: 'throw';
39
+ };
40
+ export interface AskOptions<T> {
41
+ /** Wall-clock from issue. It does NOT pause while the ask is queued. */
42
+ timeoutMs: number;
43
+ onTimeout: AskTimeoutPolicy<T>;
44
+ signal?: AbortSignal;
45
+ }
46
+ /** The two non-terminal states. `issued` never rests, so it is not observable here. */
47
+ export type AskState = 'queued' | 'delivered';
48
+ /** Why a pending ask was cancelled. Cancellation always rejects. */
49
+ export type AskCancelReason = 'signal' | 'seat-exit' | 'room-closed' | (string & {});
50
+ /** One row of {@link AskRegistry.pending}. */
51
+ export interface PendingAskView {
52
+ readonly askId: AskId;
53
+ readonly kind: string;
54
+ readonly target: ParticipantId;
55
+ readonly seat: SeatId | null;
56
+ readonly state: AskState;
57
+ /** epoch ms */
58
+ readonly issuedAt: number;
59
+ /** epoch ms */
60
+ readonly deadlineAt: number;
61
+ /** How many times the envelope has been written to a socket. */
62
+ readonly emitCount: number;
63
+ }
64
+ /**
65
+ * Counters and one gauge. Never reset.
66
+ *
67
+ * `delivered` counts EMITS, not asks — a replay advances it. `queued` is the
68
+ * odd one out: a gauge of how many asks are in `queued` right now. Mixing the
69
+ * two in one object is a small wart, documented rather than hidden.
70
+ */
71
+ export interface AskStats {
72
+ readonly issued: number;
73
+ readonly delivered: number;
74
+ readonly queued: number;
75
+ readonly replied: number;
76
+ readonly timedOut: number;
77
+ readonly cancelled: number;
78
+ /** Requirement 8. Moves in lockstep with `submitReply` returning `'dropped'`. */
79
+ readonly droppedUnknownReplies: number;
80
+ }
81
+ /**
82
+ * How an envelope reaches one socket. The registry owns no transport: it hands
83
+ * the host a participant, a socket key it was told about via
84
+ * {@link AskRegistry.attach}, and the envelope. What happens next is the host's
85
+ * business.
86
+ *
87
+ * Called once per live socket per emit, so a participant holding two sockets
88
+ * sees two calls with the same (identical, frozen) envelope object.
89
+ */
90
+ export type AskDeliverFn = (target: ParticipantId, socketKey: string, envelope: AskEnvelope) => void;
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * SPDX-License-Identifier: MIT
3
+ *
4
+ * Part of `@hadoku/room-ask`, which is MIT — the single carve-out in a repo
5
+ * that is otherwise GPL-3.0-or-later. Written clean-room from the requirement
6
+ * in `docs/requests/P4_ASK_REGISTRY.md` and from nothing else.
7
+ */
8
+ export {};
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@hadoku/room-ask",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.8",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Durable, seat-scoped request/response over a room. Transport-free: no sockets, no server, no timers you cannot drive. MIT — the one carve-out in this GPL repo.",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "dependencies": {
14
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.93"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "LICENSE"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/WolffM/hadoku-cardtable.git",
23
+ "directory": "packages/room-ask"
24
+ }
25
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.