@fuzdev/fuz_app 0.178.0 → 0.179.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/dist/actions/CLAUDE.md +106 -0
- package/dist/actions/connection_registry.d.ts +18 -0
- package/dist/actions/connection_registry.d.ts.map +1 -1
- package/dist/actions/connection_registry.js +23 -0
- package/dist/actions/room_action_specs.d.ts +733 -0
- package/dist/actions/room_action_specs.d.ts.map +1 -0
- package/dist/actions/room_action_specs.js +506 -0
- package/dist/actions/room_actions.d.ts +276 -0
- package/dist/actions/room_actions.d.ts.map +1 -0
- package/dist/actions/room_actions.js +394 -0
- package/dist/actions/room_client.svelte.d.ts +399 -0
- package/dist/actions/room_client.svelte.d.ts.map +1 -0
- package/dist/actions/room_client.svelte.js +942 -0
- package/dist/actions/room_registry.d.ts +454 -0
- package/dist/actions/room_registry.d.ts.map +1 -0
- package/dist/actions/room_registry.js +927 -0
- package/dist/auth/role_grant_offer_action_specs.d.ts +1 -1
- package/dist/auth/role_grant_queries.d.ts +17 -0
- package/dist/auth/role_grant_queries.d.ts.map +1 -1
- package/dist/auth/role_grant_queries.js +30 -0
- package/dist/rtc/rtc_mesh.svelte.d.ts +102 -0
- package/dist/rtc/rtc_mesh.svelte.d.ts.map +1 -0
- package/dist/rtc/rtc_mesh.svelte.js +232 -0
- package/dist/rtc/rtc_peer.svelte.d.ts +180 -0
- package/dist/rtc/rtc_peer.svelte.d.ts.map +1 -0
- package/dist/rtc/rtc_peer.svelte.js +397 -0
- package/dist/rtc/rtc_signal.d.ts +74 -0
- package/dist/rtc/rtc_signal.d.ts.map +1 -0
- package/dist/rtc/rtc_signal.js +87 -0
- package/dist/testing/CLAUDE.md +67 -13
- package/dist/testing/cross_backend/action_manifest.d.ts +34 -2
- package/dist/testing/cross_backend/action_manifest.d.ts.map +1 -1
- package/dist/testing/cross_backend/action_manifest.js +33 -6
- package/dist/testing/cross_backend/capabilities.d.ts +22 -4
- package/dist/testing/cross_backend/capabilities.d.ts.map +1 -1
- package/dist/testing/cross_backend/capabilities.js +4 -1
- package/dist/testing/cross_backend/full_spine_mount.d.ts +31 -6
- package/dist/testing/cross_backend/full_spine_mount.d.ts.map +1 -1
- package/dist/testing/cross_backend/full_spine_mount.js +45 -13
- package/dist/testing/cross_backend/rooms_ws.d.ts +20 -0
- package/dist/testing/cross_backend/rooms_ws.d.ts.map +1 -0
- package/dist/testing/cross_backend/rooms_ws.js +534 -0
- package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts.map +1 -1
- package/dist/testing/cross_backend/rust_spine_stub_backend_config.js +4 -1
- package/dist/testing/cross_backend/spine_suites.d.ts +5 -2
- package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
- package/dist/testing/cross_backend/spine_suites.js +24 -5
- package/dist/testing/cross_backend/spine_surface_constants.d.ts +1 -1
- package/dist/testing/cross_backend/spine_surface_constants.d.ts.map +1 -1
- package/dist/testing/cross_backend/spine_surface_constants.js +2 -1
- package/dist/testing/cross_backend/test_room_authorize.d.ts +47 -0
- package/dist/testing/cross_backend/test_room_authorize.d.ts.map +1 -0
- package/dist/testing/cross_backend/test_room_authorize.js +58 -0
- package/dist/testing/cross_backend/testing_backdoor.d.ts.map +1 -1
- package/dist/testing/cross_backend/testing_backdoor.js +10 -4
- package/dist/testing/cross_backend/testing_reset_actions.d.ts +85 -1
- package/dist/testing/cross_backend/testing_reset_actions.d.ts.map +1 -1
- package/dist/testing/cross_backend/testing_reset_actions.js +57 -3
- package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
- package/dist/testing/cross_backend/ts_spine_backend_config.js +5 -2
- package/dist/ui/AccountSessions.svelte.d.ts.map +1 -1
- package/dist/ui/AdminAccounts.svelte.d.ts.map +1 -1
- package/dist/ui/AdminAuditLog.svelte.d.ts.map +1 -1
- package/dist/ui/AdminInvites.svelte.d.ts.map +1 -1
- package/dist/ui/AdminOverview.svelte.d.ts.map +1 -1
- package/dist/ui/AdminRoleGrantHistory.svelte.d.ts.map +1 -1
- package/dist/ui/AdminSessions.svelte.d.ts.map +1 -1
- package/dist/ui/AdminSettings.svelte.d.ts.map +1 -1
- package/dist/ui/AdminSurface.svelte.d.ts.map +1 -1
- package/dist/ui/BootstrapForm.svelte.d.ts.map +1 -1
- package/dist/ui/ConfirmButton.svelte.d.ts.map +1 -1
- package/dist/ui/Datatable.svelte.d.ts.map +1 -1
- package/dist/ui/LoginForm.svelte.d.ts.map +1 -1
- package/dist/ui/LogoutButton.svelte.d.ts.map +1 -1
- package/dist/ui/OpenSignupToggle.svelte.d.ts.map +1 -1
- package/dist/ui/PopoverButton.svelte.d.ts.map +1 -1
- package/dist/ui/RoleGrantOfferForm.svelte.d.ts.map +1 -1
- package/dist/ui/RoleGrantOfferHistory.svelte.d.ts.map +1 -1
- package/dist/ui/RoleGrantOfferInbox.svelte.d.ts.map +1 -1
- package/dist/ui/SignupForm.svelte.d.ts.map +1 -1
- package/dist/ui/SurfaceExplorer.svelte.d.ts.map +1 -1
- package/package.json +18 -18
|
@@ -0,0 +1,942 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The frontend side of rooms: `RoomClient` keeps, for each room a page joins
|
|
3
|
+
* or watches, a reactive `RoomState` — its members and their state, the
|
|
4
|
+
* caller's own seat — over the WS-only `room_*` verbs and the `room_*`
|
|
5
|
+
* notifications the server pushes (`actions/room_action_specs.ts`).
|
|
6
|
+
*
|
|
7
|
+
* ## Desired state, converged one request at a time
|
|
8
|
+
*
|
|
9
|
+
* `RoomState.join`, `leave`, `watch`, `unwatch`, and `set_state` record what
|
|
10
|
+
* the page wants; one runner per room then sends whatever requests close the
|
|
11
|
+
* gap, one at a time. The server dispatches a socket's requests concurrently,
|
|
12
|
+
* so a leave sent right after a join could otherwise reach the registry first
|
|
13
|
+
* (and refuse the join as superseded), and two state sets could land out of
|
|
14
|
+
* order. A burst of calls converges: join, leave, join while the first join is
|
|
15
|
+
* in flight sends that one join, whose seat stands; a leave while seated is
|
|
16
|
+
* sent before the next join. While the socket is down nothing is sent and the
|
|
17
|
+
* wants wait for it. `RoomState.send` is the exception: it goes out at once,
|
|
18
|
+
* since a caller that cares about the order of its sends (the WebRTC mesh,
|
|
19
|
+
* `rtc/rtc_mesh.svelte.ts`) serializes them itself.
|
|
20
|
+
*
|
|
21
|
+
* Every verb runs untracked, so a page may call `join` or `watch` from an
|
|
22
|
+
* `$effect` (with `leave` or `unwatch` in its teardown) without the effect
|
|
23
|
+
* depending on the room state the verb reads and writes.
|
|
24
|
+
*
|
|
25
|
+
* Listeners are isolated: one that throws is logged and the others still
|
|
26
|
+
* hear the event, and the join, replay, or teardown that called it carries on.
|
|
27
|
+
*
|
|
28
|
+
* ## `seq`
|
|
29
|
+
*
|
|
30
|
+
* Every member event carries its room's `seq`, and a join or watch answers the
|
|
31
|
+
* room as of a `seq`. Events can arrive before that answer, so while a room's
|
|
32
|
+
* first answer is outstanding they are buffered; the answer's members are
|
|
33
|
+
* applied, then the buffer replays, dropping every event at or below the
|
|
34
|
+
* answer's `seq`. Once a room is live, an event at or below the last applied
|
|
35
|
+
* `seq` is dropped, so a connection that both watches a room and sits in it,
|
|
36
|
+
* which the server tells each event once, applies it once. A later answer
|
|
37
|
+
* whose `seq` is behind the live stream is not applied over it. A message
|
|
38
|
+
* (which reaches only a seat) that arrives on a live watch while the join is
|
|
39
|
+
* in flight is held, and delivered once the seat is taken.
|
|
40
|
+
*
|
|
41
|
+
* ## Seats lost, and reconnects
|
|
42
|
+
*
|
|
43
|
+
* `room_seat_lost` ends a seat the server took: `moved` (a newer join of the
|
|
44
|
+
* same actor took over, `moved_to` naming its room), `evicted`, or
|
|
45
|
+
* `room_closed`. None is rejoined. A socket that closes loses every seat and
|
|
46
|
+
* watch with it, and the client tells them apart: a seat lost to the
|
|
47
|
+
* disconnect is rejoined on the next connection, naming the seat it held
|
|
48
|
+
* (`rejoin_of`), and a refusal as `room_seat_moved` — the actor took a seat
|
|
49
|
+
* elsewhere meanwhile — ends it as moved, so two tabs never trade a seat back
|
|
50
|
+
* and forth. A rejoin refused `rate_limited` is retried after the refusal's
|
|
51
|
+
* `retry_after`, still naming the seat, up to `ROOM_REJOIN_RATE_LIMITED_RETRIES_MAX`
|
|
52
|
+
* times. Watches are taken again.
|
|
53
|
+
*
|
|
54
|
+
* The client learns of a new connection through `RoomRpc.connection`, an
|
|
55
|
+
* identity that changes each time the socket opens. The client follows it on
|
|
56
|
+
* its own: its constructor makes an `$effect.root` whose effect reads it and
|
|
57
|
+
* calls `sync_connection`, so a close and a reopen are seen even when they
|
|
58
|
+
* land in one batch, and `dispose` ends it. On the server the compiler makes
|
|
59
|
+
* `$effect.root` a no-op, and nothing follows; `sync_connection` stays public
|
|
60
|
+
* for that case and for tests, and runs on its own before each request and
|
|
61
|
+
* notification.
|
|
62
|
+
*
|
|
63
|
+
* ```ts
|
|
64
|
+
* const rooms = new RoomClient(create_room_rpc(socket));
|
|
65
|
+
* ```
|
|
66
|
+
*
|
|
67
|
+
* Notifications reach the client through `receive`, from the RPC client's
|
|
68
|
+
* `lookup_action_handler` for the `'receive'` phase (with
|
|
69
|
+
* `room_notification_action_specs` among the RPC client's specs):
|
|
70
|
+
*
|
|
71
|
+
* ```ts
|
|
72
|
+
* lookup_action_handler: (method, phase) =>
|
|
73
|
+
* phase === 'receive' && is_room_notification_method(method)
|
|
74
|
+
* ? (event) => rooms.receive(method, event.data.input)
|
|
75
|
+
* : undefined
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* `dispose` leaves every seat and drops every watch, for a clean teardown.
|
|
79
|
+
*
|
|
80
|
+
* @module
|
|
81
|
+
*/
|
|
82
|
+
import { to_error_message } from '@fuzdev/fuz_util/error.ts';
|
|
83
|
+
import { parse } from '@fuzdev/fuz_schema/schema.ts';
|
|
84
|
+
import { untrack } from 'svelte';
|
|
85
|
+
import { SvelteMap } from 'svelte/reactivity';
|
|
86
|
+
import { JSONRPC_ERROR_CODES, jsonrpc_error_messages, to_thrown_jsonrpc_error } from '../http/jsonrpc_errors.js';
|
|
87
|
+
import { safe_parse_dropping_unknown_keys } from '../http/schema_helpers.js';
|
|
88
|
+
import { ERROR_ROOM_JOIN_SUPERSEDED, ERROR_ROOM_NOT_JOINED, ERROR_ROOM_SEAT_MOVED, RoomJoinOutput, RoomLeaveOutput, RoomMemberJoinedParams, RoomMemberLeftParams, RoomMemberStateParams, RoomMessageParams, RoomOccupancy, RoomSeatLostParams, RoomStateSetOutput, RoomUnwatchOutput, RoomWatchEndedParams, room_join_action_spec, room_leave_action_spec, room_notification_action_specs, room_send_action_spec, room_state_set_action_spec, room_unwatch_action_spec, room_watch_action_spec } from './room_action_specs.js';
|
|
89
|
+
/**
|
|
90
|
+
* The room verbs straight over the socket's `request`, never through the RPC
|
|
91
|
+
* client's transports: those fall back to HTTP while the socket is down, and
|
|
92
|
+
* the room verbs are mounted only on a WebSocket endpoint. A request is never
|
|
93
|
+
* queued — while the socket is down it fails at once, and `RoomClient` sends
|
|
94
|
+
* it again on the next connection. Answers are parsed with the verbs' output
|
|
95
|
+
* schemas, forward-compatibly as the RPC client reads a remote result (keys a
|
|
96
|
+
* newer server added are dropped, `safe_parse_dropping_unknown_keys`); one
|
|
97
|
+
* that still doesn't parse is an `internal_error`.
|
|
98
|
+
*
|
|
99
|
+
* @param socket - the socket the room verbs go over
|
|
100
|
+
* @returns the verbs, and `connection` — the open `WebSocket`, else `null`
|
|
101
|
+
*/
|
|
102
|
+
export const create_room_rpc = (socket) => {
|
|
103
|
+
const call = (method, output) => async (input) => {
|
|
104
|
+
let result;
|
|
105
|
+
try {
|
|
106
|
+
result = await socket.request(method, input, { queue: false });
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
return {
|
|
110
|
+
ok: false,
|
|
111
|
+
error: to_thrown_jsonrpc_error(error) ??
|
|
112
|
+
jsonrpc_error_messages.internal_error(to_error_message(error))
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const parsed = safe_parse_dropping_unknown_keys(output, result);
|
|
116
|
+
if (!parsed.ok) {
|
|
117
|
+
return {
|
|
118
|
+
ok: false,
|
|
119
|
+
error: jsonrpc_error_messages.internal_error(`${method}: malformed answer`)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return { ok: true, value: parsed.value };
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
room_join: call(room_join_action_spec.method, room_join_action_spec.output),
|
|
126
|
+
room_leave: call(room_leave_action_spec.method, room_leave_action_spec.output),
|
|
127
|
+
room_send: call(room_send_action_spec.method, room_send_action_spec.output),
|
|
128
|
+
room_state_set: call(room_state_set_action_spec.method, room_state_set_action_spec.output),
|
|
129
|
+
room_watch: call(room_watch_action_spec.method, room_watch_action_spec.output),
|
|
130
|
+
room_unwatch: call(room_unwatch_action_spec.method, room_unwatch_action_spec.output),
|
|
131
|
+
get connection() {
|
|
132
|
+
return socket.connected ? socket.ws : null;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
const ROOM_NOTIFICATION_METHODS = new Set(room_notification_action_specs.map((spec) => spec.method));
|
|
137
|
+
/** Whether `method` is one of the `room_*` notifications `RoomClient.receive` takes. */
|
|
138
|
+
export const is_room_notification_method = (method) => ROOM_NOTIFICATION_METHODS.has(method);
|
|
139
|
+
/**
|
|
140
|
+
* How many times a rejoin refused `rate_limited` is retried, each after the
|
|
141
|
+
* refusal's `retry_after`, before the seat is given up as refused.
|
|
142
|
+
*/
|
|
143
|
+
export const ROOM_REJOIN_RATE_LIMITED_RETRIES_MAX = 3;
|
|
144
|
+
/** The wait before a rate-limited rejoin's retry when the refusal names none. */
|
|
145
|
+
const REJOIN_RETRY_AFTER_FALLBACK_SECONDS = 1;
|
|
146
|
+
const not_joined_error = (room_id) => jsonrpc_error_messages.conflict(`not seated in room ${room_id}`, {
|
|
147
|
+
reason: ERROR_ROOM_NOT_JOINED
|
|
148
|
+
});
|
|
149
|
+
const join_superseded_error = (room_id) => jsonrpc_error_messages.conflict(`the join of room ${room_id} was left before it was seated`, {
|
|
150
|
+
reason: ERROR_ROOM_JOIN_SUPERSEDED
|
|
151
|
+
});
|
|
152
|
+
const error_data_field = (error, key) => error.data !== null && typeof error.data === 'object'
|
|
153
|
+
? error.data[key]
|
|
154
|
+
: undefined;
|
|
155
|
+
const error_reason = (error) => error_data_field(error, 'reason');
|
|
156
|
+
/** A `rate_limited` refusal's wait in milliseconds, else `null`. */
|
|
157
|
+
const rate_limited_wait_ms = (error) => {
|
|
158
|
+
if (error.code !== JSONRPC_ERROR_CODES.rate_limited)
|
|
159
|
+
return null;
|
|
160
|
+
const retry_after = error_data_field(error, 'retry_after');
|
|
161
|
+
const seconds = typeof retry_after === 'number' && Number.isFinite(retry_after) && retry_after > 0
|
|
162
|
+
? retry_after
|
|
163
|
+
: REJOIN_RETRY_AFTER_FALLBACK_SECONDS;
|
|
164
|
+
return seconds * 1000;
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* One room as the client sees it: the members (through a seat, a watch, or
|
|
168
|
+
* both), the caller's seat, and what the page wants of it. Built by
|
|
169
|
+
* `RoomClient.room`; every verb here records a want and lets the room's runner
|
|
170
|
+
* converge on it (see the module doc).
|
|
171
|
+
*/
|
|
172
|
+
export class RoomState {
|
|
173
|
+
room_id;
|
|
174
|
+
/** The room's members in seating order, the caller's own seat included; empty until a seat or watch answers. */
|
|
175
|
+
members = $state.raw([]);
|
|
176
|
+
/** The caller's seat, or `null`. */
|
|
177
|
+
seat = $state.raw(null);
|
|
178
|
+
/** Whether a watch is live — the server answered it and hasn't ended it. */
|
|
179
|
+
watching = $state.raw(false);
|
|
180
|
+
/** Why the server last ended the seat; cleared by the next `join`. */
|
|
181
|
+
ended = $state.raw(null);
|
|
182
|
+
/** Why the server last ended the watch; cleared by the next `watch`. */
|
|
183
|
+
watch_ended = $state.raw(null);
|
|
184
|
+
/** The last refusal of a join, watch, or state set in this room; `null` once one succeeds, and cleared by the next `join`. */
|
|
185
|
+
error = $state.raw(null);
|
|
186
|
+
/** The member state the caller wants, sent with the join and with every change while seated. */
|
|
187
|
+
local_state = $state.raw(null);
|
|
188
|
+
/** Whether a seat is wanted. */
|
|
189
|
+
want_seat = $state.raw(false);
|
|
190
|
+
/** Whether a watch is wanted. */
|
|
191
|
+
want_watch = $state.raw(false);
|
|
192
|
+
/** The seat this room rejoins on the next connection, after a disconnect took it. */
|
|
193
|
+
rejoin_of = $state.raw(null);
|
|
194
|
+
/**
|
|
195
|
+
* Where the seat stands. A getter, not a `$derived`: a room outlives the
|
|
196
|
+
* effect that first asked for it, and a `$derived` would freeze with it.
|
|
197
|
+
*/
|
|
198
|
+
get seat_status() {
|
|
199
|
+
return !this.want_seat
|
|
200
|
+
? 'idle'
|
|
201
|
+
: this.seat
|
|
202
|
+
? 'joined'
|
|
203
|
+
: this.rejoin_of !== null
|
|
204
|
+
? 'rejoining'
|
|
205
|
+
: 'joining';
|
|
206
|
+
}
|
|
207
|
+
#host;
|
|
208
|
+
#listeners = new Set();
|
|
209
|
+
/** The last applied `seq`, `null` while nothing is live. */
|
|
210
|
+
#seq = null;
|
|
211
|
+
/** Events that arrived before the first answer. */
|
|
212
|
+
#buffer = [];
|
|
213
|
+
/** The join or watch in flight, whose answer will make the room live (the runner sends one request at a time). */
|
|
214
|
+
#in_flight = null;
|
|
215
|
+
/** Messages that reached a live watch while the join was in flight, for the seat it takes. */
|
|
216
|
+
#held_messages = [];
|
|
217
|
+
/** The wait before a rate-limited rejoin's retry, while one is pending. */
|
|
218
|
+
#retry_timer = null;
|
|
219
|
+
/** Rate-limited retries since the connection last changed, which starts every rejoin. */
|
|
220
|
+
#retry_attempts = 0;
|
|
221
|
+
#leave_owed = false;
|
|
222
|
+
#unwatch_owed = false;
|
|
223
|
+
/** The member state the server holds for the seat. */
|
|
224
|
+
#state_sent = null;
|
|
225
|
+
#running = false;
|
|
226
|
+
#dirty = false;
|
|
227
|
+
#idle_waiters = [];
|
|
228
|
+
#join_waiters = [];
|
|
229
|
+
/** Built by `RoomClient.room`. */
|
|
230
|
+
constructor(host, room_id) {
|
|
231
|
+
this.#host = host;
|
|
232
|
+
this.room_id = room_id;
|
|
233
|
+
host.attach(room_id, {
|
|
234
|
+
event: (event) => this.#event(event),
|
|
235
|
+
seat_lost: (params) => this.#seat_lost(params),
|
|
236
|
+
watch_ended: (params) => this.#watch_ended(params),
|
|
237
|
+
connection_lost: () => this.#connection_lost(),
|
|
238
|
+
kick: () => this.#kick(),
|
|
239
|
+
dispose: () => this.#dispose()
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Subscribe to the room's events.
|
|
244
|
+
*
|
|
245
|
+
* @returns the remover
|
|
246
|
+
*/
|
|
247
|
+
add_listener(listener) {
|
|
248
|
+
this.#listeners.add(listener);
|
|
249
|
+
return () => {
|
|
250
|
+
this.#listeners.delete(listener);
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Want a seat. Resolves once it is taken (at once when it already is), or
|
|
255
|
+
* with the refusal; a `leave` before it is taken resolves it as
|
|
256
|
+
* `room_join_superseded`. While the socket is down it waits for the next
|
|
257
|
+
* connection.
|
|
258
|
+
*
|
|
259
|
+
* @returns the seat, or why there is none
|
|
260
|
+
*/
|
|
261
|
+
join(options) {
|
|
262
|
+
return untrack(() => this.#join(options));
|
|
263
|
+
}
|
|
264
|
+
#join(options) {
|
|
265
|
+
if (this.#host.is_disposed()) {
|
|
266
|
+
return Promise.resolve({ ok: false, error: join_superseded_error(this.room_id) });
|
|
267
|
+
}
|
|
268
|
+
if (options?.state !== undefined)
|
|
269
|
+
this.local_state = options.state;
|
|
270
|
+
if (this.seat && this.want_seat) {
|
|
271
|
+
this.#kick(); // a changed state
|
|
272
|
+
return Promise.resolve({ ok: true, value: this.seat });
|
|
273
|
+
}
|
|
274
|
+
this.want_seat = true;
|
|
275
|
+
this.ended = null;
|
|
276
|
+
this.error = null;
|
|
277
|
+
const answer = new Promise((resolve) => {
|
|
278
|
+
this.#join_waiters.push(resolve);
|
|
279
|
+
});
|
|
280
|
+
this.#kick();
|
|
281
|
+
return answer;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Stop wanting the seat: it ends here at once (`unseated` with `left`), and
|
|
285
|
+
* the server hears a `room_leave` once the socket allows. A rejoin waiting
|
|
286
|
+
* on a reconnect is dropped.
|
|
287
|
+
*
|
|
288
|
+
* @returns resolves once the room's requests have settled
|
|
289
|
+
*/
|
|
290
|
+
leave() {
|
|
291
|
+
return untrack(() => this.#leave());
|
|
292
|
+
}
|
|
293
|
+
#leave() {
|
|
294
|
+
this.#release_seat('left');
|
|
295
|
+
this.#kick();
|
|
296
|
+
return this.#settled();
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Want a watch: the members without a seat. A watch the server ends
|
|
300
|
+
* (`room_watch_ended`) is not taken again.
|
|
301
|
+
*
|
|
302
|
+
* @returns resolves once the room's requests have settled
|
|
303
|
+
*/
|
|
304
|
+
watch() {
|
|
305
|
+
return untrack(() => this.#watch());
|
|
306
|
+
}
|
|
307
|
+
#watch() {
|
|
308
|
+
if (this.#host.is_disposed())
|
|
309
|
+
return Promise.resolve();
|
|
310
|
+
this.want_watch = true;
|
|
311
|
+
this.watch_ended = null;
|
|
312
|
+
this.#kick();
|
|
313
|
+
return this.#settled();
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Stop wanting the watch.
|
|
317
|
+
*
|
|
318
|
+
* @returns resolves once the room's requests have settled
|
|
319
|
+
*/
|
|
320
|
+
unwatch() {
|
|
321
|
+
return untrack(() => this.#unwatch());
|
|
322
|
+
}
|
|
323
|
+
#unwatch() {
|
|
324
|
+
this.want_watch = false;
|
|
325
|
+
this.#release_watch();
|
|
326
|
+
this.#kick();
|
|
327
|
+
return this.#settled();
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Set the caller's member state: sent now when seated, else with the next
|
|
331
|
+
* join. Only the latest state is sent; a burst sends at most one per
|
|
332
|
+
* answer.
|
|
333
|
+
*
|
|
334
|
+
* @returns resolves once the room's requests have settled
|
|
335
|
+
*/
|
|
336
|
+
set_state(state) {
|
|
337
|
+
return untrack(() => {
|
|
338
|
+
this.local_state = state;
|
|
339
|
+
this.#kick();
|
|
340
|
+
return this.#settled();
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Relay `payload` to one member (`to`), or to every other member (`null`).
|
|
345
|
+
* Sent at once, never ordered against other sends: a caller that needs an
|
|
346
|
+
* order waits for each answer before the next send.
|
|
347
|
+
*
|
|
348
|
+
* @returns `null`, or the refusal — `room_not_joined` without a seat
|
|
349
|
+
*/
|
|
350
|
+
send(to, payload) {
|
|
351
|
+
return untrack(() => {
|
|
352
|
+
// a seat on a connection that has since closed is gone
|
|
353
|
+
if (this.#host.live_connection() === null || !this.seat) {
|
|
354
|
+
return Promise.resolve({ ok: false, error: not_joined_error(this.room_id) });
|
|
355
|
+
}
|
|
356
|
+
return this.#host.rpc.room_send({
|
|
357
|
+
room_id: this.room_id,
|
|
358
|
+
to,
|
|
359
|
+
payload,
|
|
360
|
+
acting: this.#host.acting
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
// -- Inbound ------------------------------------------------------------------
|
|
365
|
+
#event(event) {
|
|
366
|
+
if (this.#seq === null) {
|
|
367
|
+
if (this.#in_flight !== null)
|
|
368
|
+
this.#buffer.push(event);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (event.params.seq <= this.#seq)
|
|
372
|
+
return;
|
|
373
|
+
this.#seq = event.params.seq;
|
|
374
|
+
if (event.method === 'room_message' &&
|
|
375
|
+
this.want_seat &&
|
|
376
|
+
!this.seat &&
|
|
377
|
+
this.#in_flight === 'join') {
|
|
378
|
+
// live through a watch, and the join that takes the seat it's for is in flight
|
|
379
|
+
this.#held_messages.push(event);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
this.#apply(event);
|
|
383
|
+
}
|
|
384
|
+
#seat_lost(params) {
|
|
385
|
+
const seat = this.seat;
|
|
386
|
+
if (!seat || seat.member_id !== params.member_id)
|
|
387
|
+
return;
|
|
388
|
+
this.#unwant_seat();
|
|
389
|
+
this.ended = { reason: params.reason, moved_to: params.moved_to };
|
|
390
|
+
this.#end_seat(seat, params.reason);
|
|
391
|
+
}
|
|
392
|
+
#watch_ended(params) {
|
|
393
|
+
if (!this.watching)
|
|
394
|
+
return;
|
|
395
|
+
this.watching = false;
|
|
396
|
+
this.want_watch = false;
|
|
397
|
+
this.watch_ended = params.reason;
|
|
398
|
+
if (!this.seat)
|
|
399
|
+
this.#reset_stream();
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* The connection the seat and watch lived on is gone: the server released
|
|
403
|
+
* both. A wanted seat is rejoined, naming the lost one.
|
|
404
|
+
*/
|
|
405
|
+
#connection_lost() {
|
|
406
|
+
const seat = this.seat;
|
|
407
|
+
this.#leave_owed = false;
|
|
408
|
+
this.#unwatch_owed = false;
|
|
409
|
+
this.#state_sent = null;
|
|
410
|
+
this.watching = false;
|
|
411
|
+
// a new connection is a fresh budget: its rejoin goes out at once
|
|
412
|
+
this.#clear_retry();
|
|
413
|
+
this.#retry_attempts = 0;
|
|
414
|
+
if (seat) {
|
|
415
|
+
if (this.want_seat)
|
|
416
|
+
this.rejoin_of = seat.member_id;
|
|
417
|
+
this.#end_seat(seat, 'disconnected');
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
this.#reset_stream();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
#dispose() {
|
|
424
|
+
// before the seat ends, so an `unseated` listener reads the watch as unwanted
|
|
425
|
+
this.want_watch = false;
|
|
426
|
+
this.#release_seat('closed');
|
|
427
|
+
this.#release_watch();
|
|
428
|
+
this.#kick();
|
|
429
|
+
return this.#settled();
|
|
430
|
+
}
|
|
431
|
+
/** Stop wanting the seat, without ending one that stands. */
|
|
432
|
+
#unwant_seat() {
|
|
433
|
+
this.want_seat = false;
|
|
434
|
+
this.rejoin_of = null;
|
|
435
|
+
this.#clear_retry();
|
|
436
|
+
}
|
|
437
|
+
/** Give up the seat here: waiting joins resolve as superseded, and a standing seat ends, owing the server a `room_leave`. */
|
|
438
|
+
#release_seat(reason) {
|
|
439
|
+
this.#unwant_seat();
|
|
440
|
+
this.#resolve_join_waiters({ ok: false, error: join_superseded_error(this.room_id) });
|
|
441
|
+
const seat = this.seat;
|
|
442
|
+
if (seat) {
|
|
443
|
+
this.#leave_owed = true;
|
|
444
|
+
this.#end_seat(seat, reason);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/** Give up a live watch here, owing the server a `room_unwatch`. */
|
|
448
|
+
#release_watch() {
|
|
449
|
+
if (!this.watching)
|
|
450
|
+
return;
|
|
451
|
+
this.watching = false;
|
|
452
|
+
this.#unwatch_owed = true;
|
|
453
|
+
if (!this.seat)
|
|
454
|
+
this.#reset_stream();
|
|
455
|
+
}
|
|
456
|
+
#apply(event) {
|
|
457
|
+
switch (event.method) {
|
|
458
|
+
case 'room_member_joined': {
|
|
459
|
+
const { member } = event.params;
|
|
460
|
+
this.members = [...this.members.filter((m) => m.member_id !== member.member_id), member];
|
|
461
|
+
this.#emit('member_joined', member);
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
case 'room_member_left': {
|
|
465
|
+
const { member_id, reason } = event.params;
|
|
466
|
+
this.members = this.members.filter((m) => m.member_id !== member_id);
|
|
467
|
+
this.#emit('member_left', member_id, reason);
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
case 'room_member_state': {
|
|
471
|
+
const member = this.#set_member_state(event.params.member_id, event.params.state);
|
|
472
|
+
if (member)
|
|
473
|
+
this.#emit('member_state', member);
|
|
474
|
+
break;
|
|
475
|
+
}
|
|
476
|
+
case 'room_message': {
|
|
477
|
+
if (!this.seat)
|
|
478
|
+
return;
|
|
479
|
+
this.#emit('message', event.params);
|
|
480
|
+
break;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
#set_member_state(member_id, state) {
|
|
485
|
+
let updated = null;
|
|
486
|
+
this.members = this.members.map((m) => {
|
|
487
|
+
if (m.member_id !== member_id)
|
|
488
|
+
return m;
|
|
489
|
+
updated = { ...m, state };
|
|
490
|
+
return updated;
|
|
491
|
+
});
|
|
492
|
+
return updated;
|
|
493
|
+
}
|
|
494
|
+
/** Apply an answer's members unless the live stream has already reached its `seq`. */
|
|
495
|
+
#apply_snapshot(seq, members) {
|
|
496
|
+
if (this.#seq === null || seq > this.#seq) {
|
|
497
|
+
this.#seq = seq;
|
|
498
|
+
this.members = members;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
#replay_buffer() {
|
|
502
|
+
const buffered = this.#buffer;
|
|
503
|
+
this.#buffer = [];
|
|
504
|
+
for (const event of buffered)
|
|
505
|
+
this.#event(event);
|
|
506
|
+
}
|
|
507
|
+
#end_seat(seat, reason) {
|
|
508
|
+
this.seat = null;
|
|
509
|
+
this.#state_sent = null;
|
|
510
|
+
if (!this.watching)
|
|
511
|
+
this.#reset_stream();
|
|
512
|
+
this.#emit('unseated', seat, reason);
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Call each listener's `name` handler, catching and logging a throw, so one
|
|
516
|
+
* listener can't stop the others, or the join, replay, or teardown that
|
|
517
|
+
* emitted.
|
|
518
|
+
*/
|
|
519
|
+
#emit(name, ...args) {
|
|
520
|
+
for (const listener of this.#listeners) {
|
|
521
|
+
const handler = listener[name];
|
|
522
|
+
if (!handler)
|
|
523
|
+
continue;
|
|
524
|
+
try {
|
|
525
|
+
handler.apply(listener, args);
|
|
526
|
+
}
|
|
527
|
+
catch (error) {
|
|
528
|
+
this.#host.log?.error('[room_client] listener failed:', this.room_id, name, error);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
#clear_retry() {
|
|
533
|
+
if (this.#retry_timer === null)
|
|
534
|
+
return;
|
|
535
|
+
this.#host.clear_timeout(this.#retry_timer);
|
|
536
|
+
this.#retry_timer = null;
|
|
537
|
+
}
|
|
538
|
+
/** Nothing is live: forget the members and the stream position. */
|
|
539
|
+
#reset_stream() {
|
|
540
|
+
this.#seq = null;
|
|
541
|
+
this.#buffer = [];
|
|
542
|
+
this.members = [];
|
|
543
|
+
}
|
|
544
|
+
#resolve_join_waiters(result) {
|
|
545
|
+
const waiters = this.#join_waiters;
|
|
546
|
+
this.#join_waiters = [];
|
|
547
|
+
for (const resolve of waiters)
|
|
548
|
+
resolve(result);
|
|
549
|
+
}
|
|
550
|
+
// -- The runner ---------------------------------------------------------------
|
|
551
|
+
#settled() {
|
|
552
|
+
if (!this.#running)
|
|
553
|
+
return Promise.resolve();
|
|
554
|
+
return new Promise((resolve) => this.#idle_waiters.push(resolve));
|
|
555
|
+
}
|
|
556
|
+
#kick() {
|
|
557
|
+
if (this.#running) {
|
|
558
|
+
this.#dirty = true;
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
void this.#run();
|
|
562
|
+
}
|
|
563
|
+
async #run() {
|
|
564
|
+
this.#running = true;
|
|
565
|
+
try {
|
|
566
|
+
for (;;) {
|
|
567
|
+
this.#dirty = false;
|
|
568
|
+
const connection = this.#host.live_connection();
|
|
569
|
+
if (connection === null)
|
|
570
|
+
break;
|
|
571
|
+
const sent = await this.#step(connection);
|
|
572
|
+
if (!sent && !this.#dirty)
|
|
573
|
+
break;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
catch (error) {
|
|
577
|
+
this.#host.log?.error('[room_client] runner failed:', this.room_id, error);
|
|
578
|
+
}
|
|
579
|
+
finally {
|
|
580
|
+
this.#running = false;
|
|
581
|
+
const waiters = this.#idle_waiters;
|
|
582
|
+
this.#idle_waiters = [];
|
|
583
|
+
for (const resolve of waiters)
|
|
584
|
+
resolve();
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Send the one request that most closes the gap, if any, in priority order:
|
|
589
|
+
* what's owed the server, then the seat, the watch, and the member state.
|
|
590
|
+
*
|
|
591
|
+
* @returns whether one was sent
|
|
592
|
+
*/
|
|
593
|
+
#step(connection) {
|
|
594
|
+
if (this.#leave_owed)
|
|
595
|
+
return this.#send_leave(connection);
|
|
596
|
+
if (this.#unwatch_owed)
|
|
597
|
+
return this.#send_unwatch(connection);
|
|
598
|
+
if (this.want_seat && !this.seat && this.#retry_timer === null) {
|
|
599
|
+
return this.#send_join(connection);
|
|
600
|
+
}
|
|
601
|
+
if (this.want_watch && !this.watching)
|
|
602
|
+
return this.#send_watch(connection);
|
|
603
|
+
const seat = this.seat;
|
|
604
|
+
const state = this.local_state;
|
|
605
|
+
if (seat && state !== null && state !== this.#state_sent) {
|
|
606
|
+
return this.#send_state(connection, seat, state);
|
|
607
|
+
}
|
|
608
|
+
return Promise.resolve(false);
|
|
609
|
+
}
|
|
610
|
+
/** Whether `connection` closed since the request on it went out. */
|
|
611
|
+
#lost(connection) {
|
|
612
|
+
return this.#host.live_connection() !== connection;
|
|
613
|
+
}
|
|
614
|
+
async #send_leave(connection) {
|
|
615
|
+
this.#leave_owed = false;
|
|
616
|
+
const result = await this.#host.rpc.room_leave({
|
|
617
|
+
room_id: this.room_id,
|
|
618
|
+
acting: this.#host.acting
|
|
619
|
+
});
|
|
620
|
+
if (!result.ok && !this.#lost(connection)) {
|
|
621
|
+
this.#host.log?.warn('[room_client] leave refused:', result.error);
|
|
622
|
+
}
|
|
623
|
+
return true;
|
|
624
|
+
}
|
|
625
|
+
async #send_unwatch(connection) {
|
|
626
|
+
this.#unwatch_owed = false;
|
|
627
|
+
const result = await this.#host.rpc.room_unwatch({
|
|
628
|
+
room_id: this.room_id,
|
|
629
|
+
acting: this.#host.acting
|
|
630
|
+
});
|
|
631
|
+
if (!result.ok && !this.#lost(connection)) {
|
|
632
|
+
this.#host.log?.warn('[room_client] unwatch refused:', result.error);
|
|
633
|
+
}
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
async #send_join(connection) {
|
|
637
|
+
const host = this.#host;
|
|
638
|
+
const room_id = this.room_id;
|
|
639
|
+
const state = this.local_state ?? undefined;
|
|
640
|
+
const rejoin_of = this.rejoin_of ?? undefined;
|
|
641
|
+
this.#in_flight = 'join';
|
|
642
|
+
let result;
|
|
643
|
+
try {
|
|
644
|
+
result = await host.rpc.room_join({ room_id, state, rejoin_of, acting: host.acting });
|
|
645
|
+
}
|
|
646
|
+
finally {
|
|
647
|
+
this.#in_flight = null;
|
|
648
|
+
}
|
|
649
|
+
const held = this.#held_messages;
|
|
650
|
+
this.#held_messages = [];
|
|
651
|
+
if (this.#lost(connection)) {
|
|
652
|
+
// seated on a connection that has since closed: the next one rejoins it
|
|
653
|
+
if (result.ok && this.want_seat)
|
|
654
|
+
this.rejoin_of = result.value.member_id;
|
|
655
|
+
if (this.#seq === null)
|
|
656
|
+
this.#buffer = [];
|
|
657
|
+
return true;
|
|
658
|
+
}
|
|
659
|
+
if (!result.ok) {
|
|
660
|
+
if (this.#seq === null)
|
|
661
|
+
this.#buffer = [];
|
|
662
|
+
if (!this.want_seat)
|
|
663
|
+
return true; // left meanwhile, already resolved
|
|
664
|
+
const wait_ms = this.rejoin_of !== null ? rate_limited_wait_ms(result.error) : null;
|
|
665
|
+
if (wait_ms !== null && this.#retry_attempts < ROOM_REJOIN_RATE_LIMITED_RETRIES_MAX) {
|
|
666
|
+
// still rejoining, naming the same seat, once the limiter allows
|
|
667
|
+
this.#retry_attempts++;
|
|
668
|
+
this.error = result.error;
|
|
669
|
+
this.#retry_timer = host.set_timeout(() => {
|
|
670
|
+
this.#retry_timer = null;
|
|
671
|
+
this.#kick();
|
|
672
|
+
}, wait_ms);
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
this.#unwant_seat();
|
|
676
|
+
this.error = result.error;
|
|
677
|
+
if (error_reason(result.error) === ERROR_ROOM_SEAT_MOVED) {
|
|
678
|
+
this.ended = { reason: 'moved', moved_to: null };
|
|
679
|
+
}
|
|
680
|
+
this.#resolve_join_waiters({ ok: false, error: result.error });
|
|
681
|
+
return true;
|
|
682
|
+
}
|
|
683
|
+
const { value } = result;
|
|
684
|
+
if (!this.want_seat) {
|
|
685
|
+
// left while the join was in flight
|
|
686
|
+
this.#leave_owed = true;
|
|
687
|
+
if (this.#seq === null)
|
|
688
|
+
this.#buffer = [];
|
|
689
|
+
return true;
|
|
690
|
+
}
|
|
691
|
+
const seat = {
|
|
692
|
+
room_id,
|
|
693
|
+
member_id: value.member_id,
|
|
694
|
+
topology: value.topology,
|
|
695
|
+
extra: value.extra
|
|
696
|
+
};
|
|
697
|
+
this.rejoin_of = null;
|
|
698
|
+
this.error = null;
|
|
699
|
+
this.#state_sent = state ?? null;
|
|
700
|
+
this.#apply_snapshot(value.seq, value.members);
|
|
701
|
+
this.seat = seat;
|
|
702
|
+
this.#emit('seated', seat);
|
|
703
|
+
this.#replay_buffer();
|
|
704
|
+
for (const event of held)
|
|
705
|
+
this.#apply(event);
|
|
706
|
+
this.#resolve_join_waiters({ ok: true, value: seat });
|
|
707
|
+
return true;
|
|
708
|
+
}
|
|
709
|
+
async #send_watch(connection) {
|
|
710
|
+
this.#in_flight = 'watch';
|
|
711
|
+
let result;
|
|
712
|
+
try {
|
|
713
|
+
result = await this.#host.rpc.room_watch({
|
|
714
|
+
room_id: this.room_id,
|
|
715
|
+
acting: this.#host.acting
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
finally {
|
|
719
|
+
this.#in_flight = null;
|
|
720
|
+
}
|
|
721
|
+
if (this.#lost(connection)) {
|
|
722
|
+
if (this.#seq === null)
|
|
723
|
+
this.#buffer = [];
|
|
724
|
+
return true;
|
|
725
|
+
}
|
|
726
|
+
if (!result.ok) {
|
|
727
|
+
if (this.#seq === null)
|
|
728
|
+
this.#buffer = [];
|
|
729
|
+
this.want_watch = false;
|
|
730
|
+
this.error = result.error;
|
|
731
|
+
return true;
|
|
732
|
+
}
|
|
733
|
+
if (!this.want_watch) {
|
|
734
|
+
this.#unwatch_owed = true;
|
|
735
|
+
if (this.#seq === null)
|
|
736
|
+
this.#buffer = [];
|
|
737
|
+
return true;
|
|
738
|
+
}
|
|
739
|
+
this.error = null;
|
|
740
|
+
this.#apply_snapshot(result.value.seq, result.value.members);
|
|
741
|
+
this.watching = true;
|
|
742
|
+
this.#replay_buffer();
|
|
743
|
+
return true;
|
|
744
|
+
}
|
|
745
|
+
async #send_state(connection, seat, state) {
|
|
746
|
+
const result = await this.#host.rpc.room_state_set({
|
|
747
|
+
room_id: this.room_id,
|
|
748
|
+
state,
|
|
749
|
+
acting: this.#host.acting
|
|
750
|
+
});
|
|
751
|
+
if (this.#lost(connection))
|
|
752
|
+
return true;
|
|
753
|
+
// recorded as sent either way, so a refused state isn't sent again in a loop
|
|
754
|
+
this.#state_sent = state;
|
|
755
|
+
if (!result.ok) {
|
|
756
|
+
this.error = result.error;
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
this.error = null;
|
|
760
|
+
// the server tells the other members, not the seat that set it
|
|
761
|
+
if (this.seat === seat) {
|
|
762
|
+
const member = this.#set_member_state(seat.member_id, state);
|
|
763
|
+
if (member)
|
|
764
|
+
this.#emit('member_state', member);
|
|
765
|
+
}
|
|
766
|
+
return true;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* The rooms one page joins and watches over one socket, for one actor. See the
|
|
771
|
+
* module doc for the wiring: the client follows the connection on its own, and
|
|
772
|
+
* `receive` takes the RPC client's room notifications.
|
|
773
|
+
*/
|
|
774
|
+
export class RoomClient {
|
|
775
|
+
rpc;
|
|
776
|
+
acting;
|
|
777
|
+
log;
|
|
778
|
+
/** Every room this client has touched, by id. */
|
|
779
|
+
rooms = new SvelteMap();
|
|
780
|
+
/** Whether `dispose` was called; the verbs then do nothing. */
|
|
781
|
+
disposed = $state.raw(false);
|
|
782
|
+
/** The connection the rooms' seats and watches live on. */
|
|
783
|
+
#connection = null;
|
|
784
|
+
#ports = new Map();
|
|
785
|
+
#host;
|
|
786
|
+
/** Ends the effect that follows `rpc.connection`. */
|
|
787
|
+
#stop_following;
|
|
788
|
+
constructor(rpc, options) {
|
|
789
|
+
this.rpc = rpc;
|
|
790
|
+
this.acting = options?.acting;
|
|
791
|
+
this.log = options?.log ?? null;
|
|
792
|
+
this.#host = {
|
|
793
|
+
rpc,
|
|
794
|
+
acting: this.acting,
|
|
795
|
+
log: this.log,
|
|
796
|
+
set_timeout: options?.set_timeout ?? ((callback, ms) => setTimeout(callback, ms)),
|
|
797
|
+
clear_timeout: options?.clear_timeout ??
|
|
798
|
+
((handle) => clearTimeout(handle)),
|
|
799
|
+
is_disposed: () => this.disposed,
|
|
800
|
+
live_connection: () => {
|
|
801
|
+
this.sync_connection();
|
|
802
|
+
return this.#connection;
|
|
803
|
+
},
|
|
804
|
+
attach: (room_id, port) => {
|
|
805
|
+
this.#ports.set(room_id, port);
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
// follow the connection, so a close and a reopen in one batch are still seen;
|
|
809
|
+
// on the server the compiler makes this a no-op
|
|
810
|
+
this.#stop_following = $effect.root(() => {
|
|
811
|
+
$effect(() => this.sync_connection());
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* The room by id, created on first use. A `$derived` or a template may ask
|
|
816
|
+
* for one it hasn't made yet, but Svelte doesn't track state made in the
|
|
817
|
+
* reaction reading it: a `$derived` that makes the room and reads its state
|
|
818
|
+
* in one expression (`client.room(id).seat_status`) never updates. Ask in
|
|
819
|
+
* one `$derived` and read in another, or make the room beforehand.
|
|
820
|
+
*
|
|
821
|
+
* @returns the room's state
|
|
822
|
+
*/
|
|
823
|
+
room(room_id) {
|
|
824
|
+
const room = this.rooms.get(room_id);
|
|
825
|
+
if (room)
|
|
826
|
+
return room;
|
|
827
|
+
// untracked, so a reaction may make a room without writing state it tracks
|
|
828
|
+
return untrack(() => {
|
|
829
|
+
const created = new RoomState(this.#host, room_id);
|
|
830
|
+
this.rooms.set(room_id, created);
|
|
831
|
+
return created;
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* Read `RoomRpc.connection`, and when it changed since the last read, drop
|
|
836
|
+
* every seat and watch the old connection held (seats lost this way are
|
|
837
|
+
* rejoined), then converge every room over the new one. The client's own
|
|
838
|
+
* effect calls it whenever the connection changes, and it runs on its own
|
|
839
|
+
* before each request and notification; only `rpc.connection` is read
|
|
840
|
+
* tracked.
|
|
841
|
+
*
|
|
842
|
+
* @mutates this - every room, when the connection changed
|
|
843
|
+
*/
|
|
844
|
+
sync_connection() {
|
|
845
|
+
const connection = this.rpc.connection;
|
|
846
|
+
untrack(() => this.#sync(connection));
|
|
847
|
+
}
|
|
848
|
+
#sync(connection) {
|
|
849
|
+
if (connection === this.#connection)
|
|
850
|
+
return;
|
|
851
|
+
const previous = this.#connection;
|
|
852
|
+
this.#connection = connection;
|
|
853
|
+
if (previous !== null) {
|
|
854
|
+
for (const port of this.#ports.values())
|
|
855
|
+
port.connection_lost();
|
|
856
|
+
}
|
|
857
|
+
if (connection !== null && !this.disposed) {
|
|
858
|
+
for (const port of this.#ports.values())
|
|
859
|
+
port.kick();
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Take a pushed notification. A room notification is parsed with its
|
|
864
|
+
* params schema and routed to its room; one for a room this client doesn't
|
|
865
|
+
* hold is dropped.
|
|
866
|
+
*
|
|
867
|
+
* @param method - the notification's method
|
|
868
|
+
* @param params - its params, unparsed
|
|
869
|
+
* @returns whether `method` is a room notification
|
|
870
|
+
*/
|
|
871
|
+
receive(method, params) {
|
|
872
|
+
if (!is_room_notification_method(method))
|
|
873
|
+
return false;
|
|
874
|
+
if (this.disposed)
|
|
875
|
+
return true;
|
|
876
|
+
this.sync_connection();
|
|
877
|
+
switch (method) {
|
|
878
|
+
case 'room_member_joined': {
|
|
879
|
+
const p = this.#parse(method, RoomMemberJoinedParams, params);
|
|
880
|
+
if (p)
|
|
881
|
+
this.#ports.get(p.room_id)?.event({ method, params: p });
|
|
882
|
+
break;
|
|
883
|
+
}
|
|
884
|
+
case 'room_member_left': {
|
|
885
|
+
const p = this.#parse(method, RoomMemberLeftParams, params);
|
|
886
|
+
if (p)
|
|
887
|
+
this.#ports.get(p.room_id)?.event({ method, params: p });
|
|
888
|
+
break;
|
|
889
|
+
}
|
|
890
|
+
case 'room_member_state': {
|
|
891
|
+
const p = this.#parse(method, RoomMemberStateParams, params);
|
|
892
|
+
if (p)
|
|
893
|
+
this.#ports.get(p.room_id)?.event({ method, params: p });
|
|
894
|
+
break;
|
|
895
|
+
}
|
|
896
|
+
case 'room_message': {
|
|
897
|
+
const p = this.#parse(method, RoomMessageParams, params);
|
|
898
|
+
if (p)
|
|
899
|
+
this.#ports.get(p.room_id)?.event({ method, params: p });
|
|
900
|
+
break;
|
|
901
|
+
}
|
|
902
|
+
case 'room_seat_lost': {
|
|
903
|
+
const p = this.#parse(method, RoomSeatLostParams, params);
|
|
904
|
+
if (p)
|
|
905
|
+
this.#ports.get(p.room_id)?.seat_lost(p);
|
|
906
|
+
break;
|
|
907
|
+
}
|
|
908
|
+
case 'room_watch_ended': {
|
|
909
|
+
const p = this.#parse(method, RoomWatchEndedParams, params);
|
|
910
|
+
if (p)
|
|
911
|
+
this.#ports.get(p.room_id)?.watch_ended(p);
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return true;
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Leave every seat and drop every watch, stop following the connection,
|
|
919
|
+
* then refuse further use. The leaves still go out: each request syncs the
|
|
920
|
+
* connection on its own.
|
|
921
|
+
*
|
|
922
|
+
* @returns resolves once the leaves have been answered (or the socket is down)
|
|
923
|
+
* @mutates this - sets `disposed`
|
|
924
|
+
*/
|
|
925
|
+
dispose() {
|
|
926
|
+
return untrack(async () => {
|
|
927
|
+
if (this.disposed)
|
|
928
|
+
return;
|
|
929
|
+
this.disposed = true;
|
|
930
|
+
this.#stop_following();
|
|
931
|
+
await Promise.all([...this.#ports.values()].map((port) => port.dispose()));
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
#parse(method, schema, params) {
|
|
935
|
+
const parsed = parse(schema, params);
|
|
936
|
+
if (!parsed.ok) {
|
|
937
|
+
this.log?.warn('[room_client] malformed notification:', method);
|
|
938
|
+
return null;
|
|
939
|
+
}
|
|
940
|
+
return parsed.value;
|
|
941
|
+
}
|
|
942
|
+
}
|