@air-jam/server 0.9.3 → 1.0.0-beta.2
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/.tsbuildinfo +1 -1
- package/dist/{chunk-PSWSCMDN.js → chunk-2BHF5ZCS.js} +2 -12
- package/dist/{chunk-PSWSCMDN.js.map → chunk-2BHF5ZCS.js.map} +1 -1
- package/dist/{chunk-LWVOQ5PH.js → chunk-5YSBR6YK.js} +3 -54
- package/dist/chunk-5YSBR6YK.js.map +1 -0
- package/dist/chunk-64G5AWIQ.js +1271 -0
- package/dist/chunk-64G5AWIQ.js.map +1 -0
- package/dist/chunk-GMZVQDC6.js +54 -0
- package/dist/chunk-GMZVQDC6.js.map +1 -0
- package/dist/chunk-ILYZVHYT.js +39 -0
- package/dist/chunk-ILYZVHYT.js.map +1 -0
- package/dist/chunk-INZKL5US.js +484 -0
- package/dist/chunk-INZKL5US.js.map +1 -0
- package/dist/chunk-JYI2GKLJ.js +334 -0
- package/dist/chunk-JYI2GKLJ.js.map +1 -0
- package/dist/cli.js +9 -7
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +15 -449
- package/dist/index.js +11 -5175
- package/dist/index.js.map +1 -1
- package/dist/process-lifecycle-A55YCNJN.js +8 -0
- package/dist/room-server-4U4TBSS5.js +13 -0
- package/dist/room-server-4U4TBSS5.js.map +1 -0
- package/dist/room-server-BO0iOvhH.d.ts +144 -0
- package/dist/room-server.d.ts +7 -0
- package/dist/room-server.js +13 -0
- package/dist/room-server.js.map +1 -0
- package/dist/room.d.ts +360 -0
- package/dist/room.js +17 -0
- package/dist/room.js.map +1 -0
- package/package.json +13 -15
- package/dist/chunk-AYTGY3H3.js +0 -67
- package/dist/chunk-AYTGY3H3.js.map +0 -1
- package/dist/chunk-LWVOQ5PH.js.map +0 -1
- package/dist/process-lifecycle-M4XOAN4Q.js +0 -8
- /package/dist/{process-lifecycle-M4XOAN4Q.js.map → process-lifecycle-A55YCNJN.js.map} +0 -0
|
@@ -0,0 +1,1271 @@
|
|
|
1
|
+
// src/room/saved-room.ts
|
|
2
|
+
var ROOM_SAVE_SCHEMA = 1;
|
|
3
|
+
|
|
4
|
+
// src/room/room.ts
|
|
5
|
+
import {
|
|
6
|
+
encodeFrame,
|
|
7
|
+
encodeHostInputFrame,
|
|
8
|
+
INPUT_FRAME_KIND,
|
|
9
|
+
MAXIMUM_SEAT_NUMBER,
|
|
10
|
+
parseHostHello,
|
|
11
|
+
parseHostToRoomFrame,
|
|
12
|
+
parsePhoneHello,
|
|
13
|
+
parsePhoneToRoomFrame,
|
|
14
|
+
PING_FRAME,
|
|
15
|
+
PONG_FRAME,
|
|
16
|
+
roomLimitsSchema,
|
|
17
|
+
seatIdFromNumber,
|
|
18
|
+
utf8ByteLength
|
|
19
|
+
} from "@air-jam/sdk/room-protocol";
|
|
20
|
+
|
|
21
|
+
// src/room/channel-copies.ts
|
|
22
|
+
import {
|
|
23
|
+
applyWeighedStatePatch,
|
|
24
|
+
isPlainObject,
|
|
25
|
+
stateWeight
|
|
26
|
+
} from "@air-jam/sdk/room-protocol";
|
|
27
|
+
var projectEntries = (entries, seat) => isPlainObject(entries) && Object.hasOwn(entries, seat) ? { [seat]: entries[seat] } : {};
|
|
28
|
+
var projectDocument = (copy, seat) => copy.private !== void 0 && Object.hasOwn(copy.document, copy.private) ? {
|
|
29
|
+
...copy.document,
|
|
30
|
+
[copy.private]: projectEntries(copy.document[copy.private], seat)
|
|
31
|
+
} : copy.document;
|
|
32
|
+
var REPAIR_RETRY_MS = 1e3;
|
|
33
|
+
var ChannelCopies = class {
|
|
34
|
+
constructor(limits) {
|
|
35
|
+
this.limits = limits;
|
|
36
|
+
}
|
|
37
|
+
copies = /* @__PURE__ */ new Map();
|
|
38
|
+
/** Channels behind the host, and when each next asks for the document. */
|
|
39
|
+
behind = /* @__PURE__ */ new Map();
|
|
40
|
+
receive(frame, now) {
|
|
41
|
+
return "document" in frame ? this.receiveDocument(frame) : this.receivePatch(frame, now);
|
|
42
|
+
}
|
|
43
|
+
/** A state frame for `channel` was dropped; the copy asks for the document at `askAt`. */
|
|
44
|
+
fellBehind(channel, askAt) {
|
|
45
|
+
if (this.behind.has(channel) || !this.holds(channel)) return;
|
|
46
|
+
this.behind.set(channel, askAt);
|
|
47
|
+
}
|
|
48
|
+
/** The channels whose ask is due at `now`; each next asks a retry later. */
|
|
49
|
+
due(now) {
|
|
50
|
+
const due = [];
|
|
51
|
+
for (const [channel, askAt] of this.behind)
|
|
52
|
+
if (askAt <= now) {
|
|
53
|
+
due.push(channel);
|
|
54
|
+
this.behind.set(channel, now + REPAIR_RETRY_MS);
|
|
55
|
+
}
|
|
56
|
+
return due;
|
|
57
|
+
}
|
|
58
|
+
/** When the next ask is due, or null when no copy is behind. */
|
|
59
|
+
nextAsk() {
|
|
60
|
+
let earliest = null;
|
|
61
|
+
for (const askAt of this.behind.values())
|
|
62
|
+
if (earliest === null || askAt < earliest) earliest = askAt;
|
|
63
|
+
return earliest;
|
|
64
|
+
}
|
|
65
|
+
drop(channel) {
|
|
66
|
+
this.behind.delete(channel);
|
|
67
|
+
return this.copies.delete(channel);
|
|
68
|
+
}
|
|
69
|
+
forHost() {
|
|
70
|
+
return [...this.copies].map(([channel, copy]) => ({
|
|
71
|
+
channel,
|
|
72
|
+
revision: copy.revision,
|
|
73
|
+
document: copy.document,
|
|
74
|
+
fingerprint: copy.fingerprint,
|
|
75
|
+
private: copy.private
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
forSeat(seat) {
|
|
79
|
+
return [...this.copies].map(([channel, copy]) => ({
|
|
80
|
+
channel,
|
|
81
|
+
revision: copy.revision,
|
|
82
|
+
document: projectDocument(copy, seat)
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
saved(channel) {
|
|
86
|
+
const copy = this.copies.get(channel);
|
|
87
|
+
return copy ? {
|
|
88
|
+
channel,
|
|
89
|
+
revision: copy.revision,
|
|
90
|
+
document: copy.document,
|
|
91
|
+
fingerprint: copy.fingerprint,
|
|
92
|
+
private: copy.private
|
|
93
|
+
} : null;
|
|
94
|
+
}
|
|
95
|
+
restore(channel) {
|
|
96
|
+
this.copies.set(channel.channel, {
|
|
97
|
+
revision: channel.revision,
|
|
98
|
+
document: channel.document,
|
|
99
|
+
fingerprint: channel.fingerprint,
|
|
100
|
+
private: channel.private,
|
|
101
|
+
weight: stateWeight(channel.document)
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
describe() {
|
|
105
|
+
return [...this.copies].map(([channel, copy]) => ({
|
|
106
|
+
channel,
|
|
107
|
+
revision: copy.revision,
|
|
108
|
+
weight: copy.weight
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
receiveDocument(frame) {
|
|
112
|
+
if (!this.holds(frame.channel)) return { kind: "too-many" };
|
|
113
|
+
const weight = stateWeight(frame.document);
|
|
114
|
+
if (weight > this.limits.stateBytes) return { kind: "too-large" };
|
|
115
|
+
const copy = {
|
|
116
|
+
revision: frame.revision,
|
|
117
|
+
document: frame.document,
|
|
118
|
+
fingerprint: frame.fingerprint,
|
|
119
|
+
private: frame.private,
|
|
120
|
+
weight
|
|
121
|
+
};
|
|
122
|
+
this.copies.set(frame.channel, copy);
|
|
123
|
+
this.behind.delete(frame.channel);
|
|
124
|
+
return {
|
|
125
|
+
kind: "applied",
|
|
126
|
+
channel: frame.channel,
|
|
127
|
+
frameFor: (seat) => ({
|
|
128
|
+
type: "state",
|
|
129
|
+
channel: frame.channel,
|
|
130
|
+
revision: frame.revision,
|
|
131
|
+
document: projectDocument(copy, seat)
|
|
132
|
+
})
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Whether `channel` has a copy, or room for one within the channel limit. */
|
|
136
|
+
holds(channel) {
|
|
137
|
+
if (this.copies.has(channel) || this.behind.has(channel)) return true;
|
|
138
|
+
let named = this.copies.size;
|
|
139
|
+
for (const name of this.behind.keys())
|
|
140
|
+
if (!this.copies.has(name)) named += 1;
|
|
141
|
+
return named < this.limits.channels;
|
|
142
|
+
}
|
|
143
|
+
receivePatch(frame, now) {
|
|
144
|
+
const copy = this.copies.get(frame.channel);
|
|
145
|
+
const applied = copy && copy.revision === frame.base ? applyWeighedStatePatch(copy.document, copy.weight, frame) : null;
|
|
146
|
+
if (!copy || !applied) {
|
|
147
|
+
if (this.behind.has(frame.channel)) return { kind: "waiting" };
|
|
148
|
+
if (!this.holds(frame.channel)) return { kind: "too-many" };
|
|
149
|
+
this.behind.set(frame.channel, now + REPAIR_RETRY_MS);
|
|
150
|
+
return { kind: "need", channel: frame.channel };
|
|
151
|
+
}
|
|
152
|
+
if (applied.weight > this.limits.stateBytes) return { kind: "too-large" };
|
|
153
|
+
copy.document = applied.document;
|
|
154
|
+
copy.weight = applied.weight;
|
|
155
|
+
copy.revision = frame.revision;
|
|
156
|
+
const privateField = copy.private;
|
|
157
|
+
return {
|
|
158
|
+
kind: "applied",
|
|
159
|
+
channel: frame.channel,
|
|
160
|
+
frameFor: (seat) => ({
|
|
161
|
+
type: "state",
|
|
162
|
+
channel: frame.channel,
|
|
163
|
+
revision: frame.revision,
|
|
164
|
+
base: frame.base,
|
|
165
|
+
set: frame.set.flatMap(
|
|
166
|
+
([path, value]) => privateField === void 0 || path[0] !== privateField ? [[path, value]] : path.length === 1 ? [[path, projectEntries(value, seat)]] : path[1] === seat ? [[path, value]] : []
|
|
167
|
+
),
|
|
168
|
+
unset: frame.unset.filter(
|
|
169
|
+
(path) => privateField === void 0 || path[0] !== privateField || path.length === 1 || path[1] === seat
|
|
170
|
+
)
|
|
171
|
+
})
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// src/room/connection-budget.ts
|
|
177
|
+
var WINDOW_MS = 1e3;
|
|
178
|
+
var FLOOD_EARNING_FACTOR = 2;
|
|
179
|
+
var FLOOD_START_SECONDS = 10;
|
|
180
|
+
var FLOOD_CAPACITY_SECONDS = 30;
|
|
181
|
+
var laneLimit = (limits, lane) => lane === "input" ? limits.inputsPerSecond : lane === "state" ? limits.statesPerSecond : limits.framesPerSecond;
|
|
182
|
+
var LANES = ["input", "state", "frame"];
|
|
183
|
+
var ConnectionBudget = class {
|
|
184
|
+
constructor(limits, now) {
|
|
185
|
+
this.limits = limits;
|
|
186
|
+
this.windowStart = now;
|
|
187
|
+
this.allowanceAt = now;
|
|
188
|
+
this.allowance = {
|
|
189
|
+
input: laneLimit(limits, "input") * FLOOD_START_SECONDS,
|
|
190
|
+
state: laneLimit(limits, "state") * FLOOD_START_SECONDS,
|
|
191
|
+
frame: laneLimit(limits, "frame") * FLOOD_START_SECONDS
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
windowStart;
|
|
195
|
+
counts = {
|
|
196
|
+
input: 0,
|
|
197
|
+
state: 0,
|
|
198
|
+
frame: 0
|
|
199
|
+
};
|
|
200
|
+
allowance;
|
|
201
|
+
allowanceAt;
|
|
202
|
+
strikes = 0;
|
|
203
|
+
/** When the current rate window ends and over-rate lanes take frames again. */
|
|
204
|
+
get windowEndsAt() {
|
|
205
|
+
return this.windowStart + WINDOW_MS;
|
|
206
|
+
}
|
|
207
|
+
admit(lane, now) {
|
|
208
|
+
if (!this.spend(lane, now)) return "flooded";
|
|
209
|
+
return this.fits(lane, now) ? "admitted" : "over-rate";
|
|
210
|
+
}
|
|
211
|
+
/** Spends one arrival from the lane's flood allowance, as a frame the room ignores does; false once it runs out. */
|
|
212
|
+
spend(lane, now) {
|
|
213
|
+
this.earn(now);
|
|
214
|
+
this.allowance[lane] -= 1;
|
|
215
|
+
return this.allowance[lane] >= 0;
|
|
216
|
+
}
|
|
217
|
+
/** Takes a frame that arrived earlier into the rate window, without spending allowance again. */
|
|
218
|
+
fits(lane, now) {
|
|
219
|
+
this.advance(now);
|
|
220
|
+
this.counts[lane] += 1;
|
|
221
|
+
return this.counts[lane] <= laneLimit(this.limits, lane);
|
|
222
|
+
}
|
|
223
|
+
/** Records a frame that did not parse; true when the connection has broken its limits. */
|
|
224
|
+
strike(now) {
|
|
225
|
+
this.advance(now);
|
|
226
|
+
this.strikes += 1;
|
|
227
|
+
return this.strikes > this.limits.strikesPerSecond;
|
|
228
|
+
}
|
|
229
|
+
earn(now) {
|
|
230
|
+
const seconds = (now - this.allowanceAt) / 1e3;
|
|
231
|
+
this.allowanceAt = now;
|
|
232
|
+
if (seconds <= 0) return;
|
|
233
|
+
for (const lane of LANES) {
|
|
234
|
+
const rate = laneLimit(this.limits, lane);
|
|
235
|
+
this.allowance[lane] = Math.min(
|
|
236
|
+
rate * FLOOD_CAPACITY_SECONDS,
|
|
237
|
+
this.allowance[lane] + rate * FLOOD_EARNING_FACTOR * seconds
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
advance(now) {
|
|
242
|
+
if (now - this.windowStart < WINDOW_MS) return;
|
|
243
|
+
this.windowStart = now;
|
|
244
|
+
this.counts.input = 0;
|
|
245
|
+
this.counts.state = 0;
|
|
246
|
+
this.counts.frame = 0;
|
|
247
|
+
this.strikes = 0;
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
// src/room/secrets.ts
|
|
252
|
+
var sameSecret = (given, expected) => {
|
|
253
|
+
let difference = given.length ^ expected.length;
|
|
254
|
+
for (let index = 0; index < expected.length; index += 1)
|
|
255
|
+
difference |= (given.charCodeAt(index % Math.max(given.length, 1)) || 0) ^ expected.charCodeAt(index);
|
|
256
|
+
return difference === 0;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// src/room/room.ts
|
|
260
|
+
var MAXIMUM_WAITING_REQUESTS = 256;
|
|
261
|
+
var PLAYER_COLORS = [
|
|
262
|
+
"#38bdf8",
|
|
263
|
+
"#a78bfa",
|
|
264
|
+
"#f472b6",
|
|
265
|
+
"#34d399",
|
|
266
|
+
"#fbbf24",
|
|
267
|
+
"#60a5fa",
|
|
268
|
+
"#c084fc",
|
|
269
|
+
"#fb7185",
|
|
270
|
+
"#4ade80",
|
|
271
|
+
"#f87171",
|
|
272
|
+
"#22d3ee",
|
|
273
|
+
"#a855f7",
|
|
274
|
+
"#ec4899",
|
|
275
|
+
"#10b981",
|
|
276
|
+
"#f59e0b",
|
|
277
|
+
"#3b82f6"
|
|
278
|
+
];
|
|
279
|
+
var Room = class _Room {
|
|
280
|
+
constructor(code, instance, hostKey, limits, labels, activityChangeable, openedAt, activity) {
|
|
281
|
+
this.code = code;
|
|
282
|
+
this.instance = instance;
|
|
283
|
+
this.hostKey = hostKey;
|
|
284
|
+
this.limits = limits;
|
|
285
|
+
this.labels = labels;
|
|
286
|
+
this.activityChangeable = activityChangeable;
|
|
287
|
+
this.openedAt = openedAt;
|
|
288
|
+
this.channels = new ChannelCopies(limits);
|
|
289
|
+
this.activity = activity;
|
|
290
|
+
this.seatsWanted = 0;
|
|
291
|
+
this.hostAwayUntil = openedAt + limits.hostGraceMs;
|
|
292
|
+
}
|
|
293
|
+
seats = /* @__PURE__ */ new Map();
|
|
294
|
+
seatsByKey = /* @__PURE__ */ new Map();
|
|
295
|
+
connections = /* @__PURE__ */ new Map();
|
|
296
|
+
channels;
|
|
297
|
+
counters = {
|
|
298
|
+
inputs: 0,
|
|
299
|
+
states: 0,
|
|
300
|
+
requests: 0,
|
|
301
|
+
signals: 0,
|
|
302
|
+
overRate: 0,
|
|
303
|
+
strikes: 0
|
|
304
|
+
};
|
|
305
|
+
/** Each phone's latest input that arrived over its rate, delivered when its rate window ends. */
|
|
306
|
+
heldInputs = /* @__PURE__ */ new Map();
|
|
307
|
+
hostConnection = null;
|
|
308
|
+
hostAwayUntil;
|
|
309
|
+
activity;
|
|
310
|
+
seatsWanted;
|
|
311
|
+
locked = false;
|
|
312
|
+
nextSeatNumber = 1;
|
|
313
|
+
closed = false;
|
|
314
|
+
roomChanged = true;
|
|
315
|
+
changedSeats = /* @__PURE__ */ new Set();
|
|
316
|
+
changedChannels = /* @__PURE__ */ new Set();
|
|
317
|
+
effects = [];
|
|
318
|
+
static open(setup, now) {
|
|
319
|
+
const room = new _Room(
|
|
320
|
+
setup.code,
|
|
321
|
+
setup.instance,
|
|
322
|
+
setup.hostKey,
|
|
323
|
+
roomLimitsSchema.parse(setup.limits),
|
|
324
|
+
setup.labels,
|
|
325
|
+
setup.activityChangeable,
|
|
326
|
+
now,
|
|
327
|
+
setup.activity
|
|
328
|
+
);
|
|
329
|
+
const effects = room.run(now, () => room.fact(now, { kind: "opened" }));
|
|
330
|
+
return { room, effects };
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Rebuilds a room from its saved state and the connections still open, as
|
|
334
|
+
* a Durable Object does when it wakes. Devices whose connection closed
|
|
335
|
+
* while the room was away are treated as having dropped now. State saved by
|
|
336
|
+
* a newer release cannot be read: every connection is told the server is
|
|
337
|
+
* restarting and there is no room.
|
|
338
|
+
*/
|
|
339
|
+
static restore(saved, live, now) {
|
|
340
|
+
if (saved.schema > ROOM_SAVE_SCHEMA)
|
|
341
|
+
return {
|
|
342
|
+
room: null,
|
|
343
|
+
effects: live.map((connection) => ({
|
|
344
|
+
close: connection,
|
|
345
|
+
reason: "restarting"
|
|
346
|
+
}))
|
|
347
|
+
};
|
|
348
|
+
const record = saved.room;
|
|
349
|
+
const room = new _Room(
|
|
350
|
+
record.code,
|
|
351
|
+
record.instance,
|
|
352
|
+
record.hostKey,
|
|
353
|
+
record.limits,
|
|
354
|
+
record.labels,
|
|
355
|
+
record.activityChangeable,
|
|
356
|
+
record.openedAt,
|
|
357
|
+
record.activity
|
|
358
|
+
);
|
|
359
|
+
room.seatsWanted = record.seatsWanted;
|
|
360
|
+
room.locked = record.locked;
|
|
361
|
+
room.nextSeatNumber = record.nextSeatNumber;
|
|
362
|
+
room.hostAwayUntil = record.hostAwayUntil;
|
|
363
|
+
room.hostConnection = record.hostConnection;
|
|
364
|
+
for (const seat of Object.values(saved.seats)) {
|
|
365
|
+
room.seats.set(seat.id, { ...seat });
|
|
366
|
+
room.seatsByKey.set(seat.key, seat.id);
|
|
367
|
+
}
|
|
368
|
+
for (const channel of Object.values(saved.channels))
|
|
369
|
+
room.channels.restore(channel);
|
|
370
|
+
room.roomChanged = false;
|
|
371
|
+
room.reconnect(new Set(live), now);
|
|
372
|
+
room.settle(now);
|
|
373
|
+
if (room.hostConnection !== null)
|
|
374
|
+
room.toPhones({ type: "host", present: true });
|
|
375
|
+
return { room, effects: room.effects };
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* A device's first frame. `role` comes from the path it connected to, so
|
|
379
|
+
* the path alone decides who may act as a host.
|
|
380
|
+
*/
|
|
381
|
+
connect(connection, role, hello, now) {
|
|
382
|
+
return this.run(now, () => {
|
|
383
|
+
if (this.connections.has(connection))
|
|
384
|
+
throw new Error(`Connection ${connection} already said hello.`);
|
|
385
|
+
if (this.closed) return this.closeConnection(connection, "closed");
|
|
386
|
+
if (utf8ByteLength(hello) > this.limits.frameBytes)
|
|
387
|
+
return this.closeConnection(connection, "limits-broken");
|
|
388
|
+
if (role === "host") {
|
|
389
|
+
const frame = parseHostHello(hello);
|
|
390
|
+
if (!frame)
|
|
391
|
+
return this.closeConnection(connection, "unsupported-version");
|
|
392
|
+
this.connectHost(connection, frame, now);
|
|
393
|
+
} else {
|
|
394
|
+
const frame = parsePhoneHello(hello);
|
|
395
|
+
if (!frame)
|
|
396
|
+
return this.closeConnection(connection, "unsupported-version");
|
|
397
|
+
this.connectPhone(connection, frame, now);
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
receive(connection, data, now) {
|
|
402
|
+
return this.run(now, () => {
|
|
403
|
+
const entry = this.connections.get(connection);
|
|
404
|
+
if (!entry) return;
|
|
405
|
+
if (data === PING_FRAME) {
|
|
406
|
+
if (!entry.budget.spend("frame", now))
|
|
407
|
+
return this.breakLimits(connection, entry, now);
|
|
408
|
+
return this.send(connection, PONG_FRAME);
|
|
409
|
+
}
|
|
410
|
+
if (typeof data === "string") {
|
|
411
|
+
if (entry.role === "host")
|
|
412
|
+
this.receiveHostText(connection, entry, data, now);
|
|
413
|
+
else this.receivePhoneText(connection, entry, data, now);
|
|
414
|
+
} else if (entry.role === "phone") {
|
|
415
|
+
this.receiveInput(connection, entry, data, now);
|
|
416
|
+
} else this.ignore(connection, entry, "unknown", "frame", now);
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
disconnect(connection, now) {
|
|
420
|
+
return this.run(now, () => {
|
|
421
|
+
const entry = this.connections.get(connection);
|
|
422
|
+
if (!entry) return;
|
|
423
|
+
this.connections.delete(connection);
|
|
424
|
+
this.release(entry, now);
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
wake(now) {
|
|
428
|
+
return this.run(now, () => {
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
stop(reason, now) {
|
|
432
|
+
return this.run(now, () => {
|
|
433
|
+
if (!this.closed) this.closeRoom(reason, now);
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
/** The earliest moment something is due, or null once the room is closed. */
|
|
437
|
+
nextWake() {
|
|
438
|
+
if (this.closed) return null;
|
|
439
|
+
let earliest = this.openedAt + this.limits.maximumAgeMs;
|
|
440
|
+
if (this.hostAwayUntil !== null)
|
|
441
|
+
earliest = Math.min(earliest, this.hostAwayUntil);
|
|
442
|
+
for (const seat of this.seats.values())
|
|
443
|
+
if (seat.holdUntil !== null)
|
|
444
|
+
earliest = Math.min(earliest, seat.holdUntil);
|
|
445
|
+
for (const connection of this.heldInputs.keys()) {
|
|
446
|
+
const entry = this.connections.get(connection);
|
|
447
|
+
if (entry) earliest = Math.min(earliest, entry.budget.windowEndsAt);
|
|
448
|
+
}
|
|
449
|
+
const ask = this.hostConnection === null ? null : this.channels.nextAsk();
|
|
450
|
+
if (ask !== null) earliest = Math.min(earliest, ask);
|
|
451
|
+
return earliest;
|
|
452
|
+
}
|
|
453
|
+
save() {
|
|
454
|
+
if (!this.roomChanged && this.changedSeats.size === 0 && this.changedChannels.size === 0)
|
|
455
|
+
return null;
|
|
456
|
+
const changes = {
|
|
457
|
+
schema: ROOM_SAVE_SCHEMA,
|
|
458
|
+
...this.roomChanged ? { room: this.record() } : {},
|
|
459
|
+
seats: Object.fromEntries(
|
|
460
|
+
[...this.changedSeats].map((id) => {
|
|
461
|
+
const seat = this.seats.get(id);
|
|
462
|
+
return [id, seat ? this.savedSeat(seat) : null];
|
|
463
|
+
})
|
|
464
|
+
),
|
|
465
|
+
channels: Object.fromEntries(
|
|
466
|
+
[...this.changedChannels].map((channel) => [
|
|
467
|
+
channel,
|
|
468
|
+
this.channels.saved(channel)
|
|
469
|
+
])
|
|
470
|
+
)
|
|
471
|
+
};
|
|
472
|
+
this.roomChanged = false;
|
|
473
|
+
this.changedSeats.clear();
|
|
474
|
+
this.changedChannels.clear();
|
|
475
|
+
return changes;
|
|
476
|
+
}
|
|
477
|
+
describe() {
|
|
478
|
+
return {
|
|
479
|
+
code: this.code,
|
|
480
|
+
instance: this.instance,
|
|
481
|
+
labels: this.labels,
|
|
482
|
+
openedAt: this.openedAt,
|
|
483
|
+
closed: this.closed,
|
|
484
|
+
activity: this.activity,
|
|
485
|
+
limits: this.limits,
|
|
486
|
+
seatsWanted: this.seatsWanted,
|
|
487
|
+
locked: this.locked,
|
|
488
|
+
host: {
|
|
489
|
+
connected: this.hostConnection !== null,
|
|
490
|
+
awayUntil: this.hostAwayUntil
|
|
491
|
+
},
|
|
492
|
+
seats: [...this.seats.values()].map((seat) => ({
|
|
493
|
+
id: seat.id,
|
|
494
|
+
kind: seat.kind,
|
|
495
|
+
label: seat.localSeatLabel ?? seat.label,
|
|
496
|
+
connected: seat.connection !== null,
|
|
497
|
+
holdUntil: seat.holdUntil
|
|
498
|
+
})),
|
|
499
|
+
channels: this.channels.describe(),
|
|
500
|
+
counters: { ...this.counters }
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
run(now, work) {
|
|
504
|
+
this.effects = [];
|
|
505
|
+
this.settle(now);
|
|
506
|
+
work();
|
|
507
|
+
this.settle(now);
|
|
508
|
+
return this.effects;
|
|
509
|
+
}
|
|
510
|
+
settle(now) {
|
|
511
|
+
if (this.closed) return;
|
|
512
|
+
const expiresAt = this.openedAt + this.limits.maximumAgeMs;
|
|
513
|
+
const hostGoneAt = this.hostAwayUntil ?? Number.POSITIVE_INFINITY;
|
|
514
|
+
if (now >= Math.min(expiresAt, hostGoneAt))
|
|
515
|
+
return hostGoneAt < expiresAt ? this.closeRoom("host-gone", hostGoneAt) : this.closeRoom("expired", expiresAt);
|
|
516
|
+
for (const seat of [...this.seats.values()])
|
|
517
|
+
if (seat.holdUntil !== null && now >= seat.holdUntil)
|
|
518
|
+
this.freeSeat(seat, "dropped", seat.holdUntil);
|
|
519
|
+
for (const [connection, frame] of [...this.heldInputs]) {
|
|
520
|
+
const entry = this.connections.get(connection);
|
|
521
|
+
if (entry?.role !== "phone") {
|
|
522
|
+
this.heldInputs.delete(connection);
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (now < entry.budget.windowEndsAt) continue;
|
|
526
|
+
this.heldInputs.delete(connection);
|
|
527
|
+
if (entry.budget.fits("input", now)) this.forwardInput(entry, frame);
|
|
528
|
+
}
|
|
529
|
+
if (this.hostConnection !== null)
|
|
530
|
+
for (const channel of this.channels.due(now))
|
|
531
|
+
this.send(this.hostConnection, { type: "need", channel });
|
|
532
|
+
}
|
|
533
|
+
reconnect(live, now) {
|
|
534
|
+
const hostDropped = this.hostConnection !== null && !live.has(this.hostConnection);
|
|
535
|
+
if (hostDropped) this.hostConnection = null;
|
|
536
|
+
const droppedSeats = [];
|
|
537
|
+
for (const seat of this.seats.values())
|
|
538
|
+
if (seat.connection !== null && !live.has(seat.connection)) {
|
|
539
|
+
seat.connection = null;
|
|
540
|
+
droppedSeats.push(seat);
|
|
541
|
+
}
|
|
542
|
+
if (this.hostConnection !== null)
|
|
543
|
+
this.connections.set(this.hostConnection, {
|
|
544
|
+
role: "host",
|
|
545
|
+
budget: new ConnectionBudget(this.limits, now)
|
|
546
|
+
});
|
|
547
|
+
for (const seat of this.seats.values())
|
|
548
|
+
if (seat.connection !== null)
|
|
549
|
+
this.connections.set(seat.connection, {
|
|
550
|
+
role: "phone",
|
|
551
|
+
seat: seat.id,
|
|
552
|
+
budget: new ConnectionBudget(this.limits, now),
|
|
553
|
+
requests: null
|
|
554
|
+
});
|
|
555
|
+
if (hostDropped) this.hostLeft(now);
|
|
556
|
+
for (const seat of droppedSeats) this.seatLeft(seat, now);
|
|
557
|
+
}
|
|
558
|
+
connectHost(connection, hello, now) {
|
|
559
|
+
if (hello.instance !== void 0 && hello.instance !== this.instance)
|
|
560
|
+
return this.closeConnection(connection, "not-found");
|
|
561
|
+
if (!sameSecret(hello.key, this.hostKey))
|
|
562
|
+
return this.closeConnection(connection, "unauthorised");
|
|
563
|
+
if (this.hostConnection !== null) {
|
|
564
|
+
this.connections.delete(this.hostConnection);
|
|
565
|
+
this.closeConnection(this.hostConnection, "replaced");
|
|
566
|
+
}
|
|
567
|
+
this.hostConnection = connection;
|
|
568
|
+
this.hostAwayUntil = null;
|
|
569
|
+
this.connections.set(connection, {
|
|
570
|
+
role: "host",
|
|
571
|
+
budget: new ConnectionBudget(this.limits, now)
|
|
572
|
+
});
|
|
573
|
+
this.seatsWanted = Math.min(hello.seats, this.limits.seats);
|
|
574
|
+
this.roomChanged = true;
|
|
575
|
+
this.send(connection, {
|
|
576
|
+
type: "welcome",
|
|
577
|
+
code: this.code,
|
|
578
|
+
instance: this.instance,
|
|
579
|
+
seats: this.seatViews(),
|
|
580
|
+
channels: this.channels.forHost(),
|
|
581
|
+
limits: this.limits,
|
|
582
|
+
features: [],
|
|
583
|
+
seatsWanted: this.seatsWanted,
|
|
584
|
+
locked: this.locked,
|
|
585
|
+
activity: this.activity
|
|
586
|
+
});
|
|
587
|
+
this.toPhones({ type: "host", present: true });
|
|
588
|
+
}
|
|
589
|
+
connectPhone(connection, hello, now) {
|
|
590
|
+
if (hello.instance !== void 0 && hello.instance !== this.instance)
|
|
591
|
+
return this.closeConnection(connection, "not-found");
|
|
592
|
+
const existingId = this.seatsByKey.get(hello.key);
|
|
593
|
+
let seat = existingId === void 0 ? void 0 : this.seats.get(existingId);
|
|
594
|
+
let resumed = null;
|
|
595
|
+
let inputBaseline = false;
|
|
596
|
+
if (seat) {
|
|
597
|
+
inputBaseline = hello.page !== seat.page;
|
|
598
|
+
if (seat.connection !== null) {
|
|
599
|
+
this.connections.delete(seat.connection);
|
|
600
|
+
this.closeConnection(seat.connection, "replaced");
|
|
601
|
+
} else resumed = true;
|
|
602
|
+
const profile = hello.profile ?? {};
|
|
603
|
+
if (profile.label !== void 0) seat.label = profile.label;
|
|
604
|
+
if (profile.avatarId !== void 0) seat.avatarId = profile.avatarId;
|
|
605
|
+
seat.localSeatLabel = profile.localSeatLabel;
|
|
606
|
+
} else {
|
|
607
|
+
if (hello.instance !== void 0)
|
|
608
|
+
return this.closeConnection(connection, "not-found");
|
|
609
|
+
if (this.locked || this.seats.size >= this.seatsWanted || this.nextSeatNumber > MAXIMUM_SEAT_NUMBER)
|
|
610
|
+
return this.closeConnection(connection, "full");
|
|
611
|
+
seat = this.createSeat(hello);
|
|
612
|
+
resumed = false;
|
|
613
|
+
}
|
|
614
|
+
seat.page = hello.page;
|
|
615
|
+
seat.connection = connection;
|
|
616
|
+
seat.holdUntil = null;
|
|
617
|
+
this.changedSeats.add(seat.id);
|
|
618
|
+
this.connections.set(connection, {
|
|
619
|
+
role: "phone",
|
|
620
|
+
seat: seat.id,
|
|
621
|
+
budget: new ConnectionBudget(this.limits, now),
|
|
622
|
+
requests: /* @__PURE__ */ new Set()
|
|
623
|
+
});
|
|
624
|
+
this.send(connection, {
|
|
625
|
+
type: "welcome",
|
|
626
|
+
code: this.code,
|
|
627
|
+
instance: this.instance,
|
|
628
|
+
seat: seat.id,
|
|
629
|
+
seats: this.seatViews(),
|
|
630
|
+
channels: this.channels.forSeat(seat.id),
|
|
631
|
+
limits: this.limits,
|
|
632
|
+
features: [],
|
|
633
|
+
host: this.hostConnection !== null
|
|
634
|
+
});
|
|
635
|
+
this.announceSeat(seat, seat.id, inputBaseline);
|
|
636
|
+
if (resumed !== null)
|
|
637
|
+
this.fact(now, {
|
|
638
|
+
kind: "seat-joined",
|
|
639
|
+
seat: seat.id,
|
|
640
|
+
seatKind: seat.kind,
|
|
641
|
+
resumed
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
createSeat(hello) {
|
|
645
|
+
const seatNumber = this.nextSeatNumber;
|
|
646
|
+
this.nextSeatNumber += 1;
|
|
647
|
+
this.roomChanged = true;
|
|
648
|
+
const colorsInUse = new Set(
|
|
649
|
+
[...this.seats.values()].map((seat2) => seat2.color)
|
|
650
|
+
);
|
|
651
|
+
const seat = {
|
|
652
|
+
id: seatIdFromNumber(seatNumber),
|
|
653
|
+
key: hello.key,
|
|
654
|
+
kind: hello.kind,
|
|
655
|
+
label: hello.profile?.label ?? `Player ${seatNumber}`,
|
|
656
|
+
localSeatLabel: hello.profile?.localSeatLabel,
|
|
657
|
+
avatarId: hello.profile?.avatarId,
|
|
658
|
+
color: PLAYER_COLORS.find((color) => !colorsInUse.has(color)) ?? PLAYER_COLORS[(seatNumber - 1) % PLAYER_COLORS.length] ?? PLAYER_COLORS[0],
|
|
659
|
+
connection: null,
|
|
660
|
+
holdUntil: null
|
|
661
|
+
};
|
|
662
|
+
this.seats.set(seat.id, seat);
|
|
663
|
+
this.seatsByKey.set(seat.key, seat.id);
|
|
664
|
+
return seat;
|
|
665
|
+
}
|
|
666
|
+
receiveHostText(connection, entry, text, now) {
|
|
667
|
+
const bytes = utf8ByteLength(text);
|
|
668
|
+
if (bytes > this.limits.stateBytes)
|
|
669
|
+
return this.breakLimits(connection, entry, now);
|
|
670
|
+
const parsed = parseHostToRoomFrame(text);
|
|
671
|
+
if (parsed.status !== "frame")
|
|
672
|
+
return this.ignore(connection, entry, parsed.status, "frame", now);
|
|
673
|
+
const frame = parsed.frame;
|
|
674
|
+
if (frame.type !== "state" && bytes > this.limits.frameBytes)
|
|
675
|
+
return this.breakLimits(connection, entry, now);
|
|
676
|
+
const admission = entry.budget.admit(
|
|
677
|
+
frame.type === "state" ? "state" : "frame",
|
|
678
|
+
now
|
|
679
|
+
);
|
|
680
|
+
if (admission === "flooded")
|
|
681
|
+
return this.breakLimits(connection, entry, now);
|
|
682
|
+
if (admission === "over-rate") {
|
|
683
|
+
this.counters.overRate += 1;
|
|
684
|
+
if (frame.type === "state")
|
|
685
|
+
this.channels.fellBehind(frame.channel, entry.budget.windowEndsAt);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
this.handleHostFrame(connection, entry, frame, now);
|
|
689
|
+
}
|
|
690
|
+
handleHostFrame(connection, entry, frame, now) {
|
|
691
|
+
switch (frame.type) {
|
|
692
|
+
case "state": {
|
|
693
|
+
this.counters.states += 1;
|
|
694
|
+
const outcome = this.channels.receive(frame, now);
|
|
695
|
+
if (outcome.kind === "applied") {
|
|
696
|
+
this.changedChannels.add(outcome.channel);
|
|
697
|
+
for (const seat of this.seats.values())
|
|
698
|
+
if (seat.connection !== null)
|
|
699
|
+
this.send(seat.connection, outcome.frameFor(seat.id));
|
|
700
|
+
} else if (outcome.kind === "need") {
|
|
701
|
+
this.send(connection, { type: "need", channel: outcome.channel });
|
|
702
|
+
} else if (outcome.kind !== "waiting") {
|
|
703
|
+
this.breakLimits(connection, entry, now);
|
|
704
|
+
}
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
case "response": {
|
|
708
|
+
const asker = this.seats.get(frame.seat)?.connection ?? null;
|
|
709
|
+
const phone = asker === null ? void 0 : this.connections.get(asker);
|
|
710
|
+
if (asker !== null && phone?.role === "phone" && (phone.requests === null || phone.requests.delete(frame.id)))
|
|
711
|
+
this.send(asker, {
|
|
712
|
+
type: "response",
|
|
713
|
+
id: frame.id,
|
|
714
|
+
result: frame.result
|
|
715
|
+
});
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
case "signal": {
|
|
719
|
+
this.counters.signals += 1;
|
|
720
|
+
const signal = {
|
|
721
|
+
type: "signal",
|
|
722
|
+
kind: frame.kind,
|
|
723
|
+
payload: frame.payload
|
|
724
|
+
};
|
|
725
|
+
if (frame.seat === void 0) return this.toPhones(signal);
|
|
726
|
+
const seat = this.seats.get(frame.seat);
|
|
727
|
+
if (seat?.connection) this.send(seat.connection, signal);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
case "room":
|
|
731
|
+
if (frame.seats !== void 0)
|
|
732
|
+
this.seatsWanted = Math.min(frame.seats, this.limits.seats);
|
|
733
|
+
if (frame.locked !== void 0) this.locked = frame.locked;
|
|
734
|
+
this.roomChanged = true;
|
|
735
|
+
return;
|
|
736
|
+
case "remove": {
|
|
737
|
+
const seat = this.seats.get(frame.seat);
|
|
738
|
+
if (!seat) return;
|
|
739
|
+
if (seat.connection !== null) {
|
|
740
|
+
this.connections.delete(seat.connection);
|
|
741
|
+
this.closeConnection(seat.connection, "removed");
|
|
742
|
+
}
|
|
743
|
+
return this.freeSeat(seat, "removed", now);
|
|
744
|
+
}
|
|
745
|
+
case "drop":
|
|
746
|
+
if (!this.channels.drop(frame.channel)) return;
|
|
747
|
+
this.changedChannels.add(frame.channel);
|
|
748
|
+
return this.toPhones({ type: "drop", channel: frame.channel });
|
|
749
|
+
case "activity": {
|
|
750
|
+
if (!this.activityChangeable)
|
|
751
|
+
return this.strike(connection, entry, now);
|
|
752
|
+
if (frame.activity === this.activity) return;
|
|
753
|
+
const previous = this.activity;
|
|
754
|
+
this.activity = frame.activity;
|
|
755
|
+
this.roomChanged = true;
|
|
756
|
+
return this.fact(now, {
|
|
757
|
+
kind: "activity",
|
|
758
|
+
activity: frame.activity,
|
|
759
|
+
previous
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
case "end":
|
|
763
|
+
return this.closeRoom("ended", now);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
receivePhoneText(connection, entry, text, now) {
|
|
767
|
+
if (utf8ByteLength(text) > this.limits.frameBytes)
|
|
768
|
+
return this.breakLimits(connection, entry, now);
|
|
769
|
+
const parsed = parsePhoneToRoomFrame(text);
|
|
770
|
+
if (parsed.status !== "frame")
|
|
771
|
+
return this.ignore(connection, entry, parsed.status, "frame", now);
|
|
772
|
+
const admission = entry.budget.admit("frame", now);
|
|
773
|
+
if (admission === "flooded")
|
|
774
|
+
return this.breakLimits(connection, entry, now);
|
|
775
|
+
if (admission === "over-rate") {
|
|
776
|
+
this.counters.overRate += 1;
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
this.handlePhoneFrame(connection, entry, parsed.frame, now);
|
|
780
|
+
}
|
|
781
|
+
handlePhoneFrame(connection, entry, frame, now) {
|
|
782
|
+
const seatId = entry.seat;
|
|
783
|
+
const seat = this.seats.get(seatId);
|
|
784
|
+
if (!seat) throw new Error(`Connection ${connection} has no seat.`);
|
|
785
|
+
switch (frame.type) {
|
|
786
|
+
case "request":
|
|
787
|
+
this.counters.requests += 1;
|
|
788
|
+
if (this.hostConnection === null)
|
|
789
|
+
return this.send(connection, {
|
|
790
|
+
type: "response",
|
|
791
|
+
id: frame.id,
|
|
792
|
+
refused: "host-away"
|
|
793
|
+
});
|
|
794
|
+
if (entry.requests) {
|
|
795
|
+
const oldest = entry.requests.values().next();
|
|
796
|
+
if (entry.requests.size >= MAXIMUM_WAITING_REQUESTS && !oldest.done)
|
|
797
|
+
entry.requests.delete(oldest.value);
|
|
798
|
+
entry.requests.add(frame.id);
|
|
799
|
+
}
|
|
800
|
+
return this.send(this.hostConnection, {
|
|
801
|
+
type: "request",
|
|
802
|
+
seat: seatId,
|
|
803
|
+
id: frame.id,
|
|
804
|
+
channel: frame.channel,
|
|
805
|
+
name: frame.name,
|
|
806
|
+
payload: frame.payload
|
|
807
|
+
});
|
|
808
|
+
case "profile":
|
|
809
|
+
if (frame.label !== void 0) seat.label = frame.label;
|
|
810
|
+
if (frame.avatarId !== void 0) seat.avatarId = frame.avatarId;
|
|
811
|
+
this.changedSeats.add(seatId);
|
|
812
|
+
return this.announceSeat(seat, null);
|
|
813
|
+
case "leave":
|
|
814
|
+
this.connections.delete(connection);
|
|
815
|
+
this.closeConnection(connection, "left");
|
|
816
|
+
return this.freeSeat(seat, "left", now);
|
|
817
|
+
case "baseline":
|
|
818
|
+
return this.toHost({
|
|
819
|
+
type: "seat",
|
|
820
|
+
seat: this.seatView(seat),
|
|
821
|
+
inputBaseline: true
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
receiveInput(connection, entry, frame, now) {
|
|
826
|
+
if (frame[0] !== INPUT_FRAME_KIND)
|
|
827
|
+
return this.ignore(connection, entry, "unknown", "input", now);
|
|
828
|
+
if (frame.byteLength - 1 > this.limits.inputBytes)
|
|
829
|
+
return this.breakLimits(connection, entry, now);
|
|
830
|
+
const admission = entry.budget.admit("input", now);
|
|
831
|
+
if (admission === "flooded")
|
|
832
|
+
return this.breakLimits(connection, entry, now);
|
|
833
|
+
if (admission === "over-rate") {
|
|
834
|
+
this.counters.overRate += 1;
|
|
835
|
+
this.heldInputs.set(connection, frame);
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
this.heldInputs.delete(connection);
|
|
839
|
+
this.forwardInput(entry, frame);
|
|
840
|
+
}
|
|
841
|
+
forwardInput(entry, frame) {
|
|
842
|
+
if (this.hostConnection === null) return;
|
|
843
|
+
this.counters.inputs += 1;
|
|
844
|
+
this.send(this.hostConnection, encodeHostInputFrame(entry.seat, frame));
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* A frame the room does not act on still spends its lane's flood
|
|
848
|
+
* allowance; one that does not parse is also a strike, and one nested too
|
|
849
|
+
* deep breaks the limits outright.
|
|
850
|
+
*/
|
|
851
|
+
ignore(connection, entry, status, lane, now) {
|
|
852
|
+
if (status === "too-deep" || !entry.budget.spend(lane, now))
|
|
853
|
+
return this.breakLimits(connection, entry, now);
|
|
854
|
+
if (status === "invalid") this.strike(connection, entry, now);
|
|
855
|
+
}
|
|
856
|
+
strike(connection, entry, now) {
|
|
857
|
+
this.counters.strikes += 1;
|
|
858
|
+
if (entry.budget.strike(now)) this.breakLimits(connection, entry, now);
|
|
859
|
+
}
|
|
860
|
+
/** Sizes are a property of the content, so a breach is final rather than counted. */
|
|
861
|
+
breakLimits(connection, entry, now) {
|
|
862
|
+
this.connections.delete(connection);
|
|
863
|
+
this.closeConnection(connection, "limits-broken");
|
|
864
|
+
this.release(entry, now);
|
|
865
|
+
}
|
|
866
|
+
/** What follows a connection ending while its host or seat stays. */
|
|
867
|
+
release(entry, now) {
|
|
868
|
+
if (entry.role === "host") return this.hostLeft(now);
|
|
869
|
+
const seat = this.seats.get(entry.seat);
|
|
870
|
+
if (seat) this.seatLeft(seat, now);
|
|
871
|
+
}
|
|
872
|
+
hostLeft(now) {
|
|
873
|
+
this.hostConnection = null;
|
|
874
|
+
this.hostAwayUntil = now + this.limits.hostGraceMs;
|
|
875
|
+
this.roomChanged = true;
|
|
876
|
+
this.toPhones({ type: "host", present: false });
|
|
877
|
+
}
|
|
878
|
+
seatLeft(seat, now) {
|
|
879
|
+
seat.connection = null;
|
|
880
|
+
const hold = seat.kind === "agent" ? 0 : this.limits.seatHoldMs;
|
|
881
|
+
if (hold === 0) return this.freeSeat(seat, "dropped", now);
|
|
882
|
+
seat.holdUntil = now + hold;
|
|
883
|
+
this.changedSeats.add(seat.id);
|
|
884
|
+
this.announceSeat(seat, null);
|
|
885
|
+
this.fact(now, { kind: "seat-dropped", seat: seat.id });
|
|
886
|
+
}
|
|
887
|
+
freeSeat(seat, cause, at) {
|
|
888
|
+
this.seats.delete(seat.id);
|
|
889
|
+
this.seatsByKey.delete(seat.key);
|
|
890
|
+
this.changedSeats.add(seat.id);
|
|
891
|
+
const left = { type: "left", seat: seat.id };
|
|
892
|
+
this.toHost(left);
|
|
893
|
+
this.toPhones(left);
|
|
894
|
+
this.fact(at, { kind: "seat-left", seat: seat.id, cause });
|
|
895
|
+
}
|
|
896
|
+
closeRoom(cause, at) {
|
|
897
|
+
const reason = cause === "restarting" ? "restarting" : "closed";
|
|
898
|
+
for (const connection of this.connections.keys())
|
|
899
|
+
this.closeConnection(connection, reason);
|
|
900
|
+
this.connections.clear();
|
|
901
|
+
this.hostConnection = null;
|
|
902
|
+
this.closed = true;
|
|
903
|
+
this.fact(at, { kind: "closed", cause });
|
|
904
|
+
}
|
|
905
|
+
announceSeat(seat, except, inputBaseline = false) {
|
|
906
|
+
const frame = { type: "seat", seat: this.seatView(seat) };
|
|
907
|
+
this.toHost(inputBaseline ? { ...frame, inputBaseline: true } : frame);
|
|
908
|
+
for (const other of this.seats.values())
|
|
909
|
+
if (other.id !== except && other.connection !== null)
|
|
910
|
+
this.send(other.connection, frame);
|
|
911
|
+
}
|
|
912
|
+
seatView(seat) {
|
|
913
|
+
return {
|
|
914
|
+
id: seat.id,
|
|
915
|
+
label: seat.localSeatLabel ?? seat.label,
|
|
916
|
+
color: seat.color,
|
|
917
|
+
avatarId: seat.avatarId,
|
|
918
|
+
kind: seat.kind,
|
|
919
|
+
connected: seat.connection !== null
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
seatViews() {
|
|
923
|
+
return [...this.seats.values()].map((seat) => this.seatView(seat));
|
|
924
|
+
}
|
|
925
|
+
toHost(frame) {
|
|
926
|
+
if (this.hostConnection !== null) this.send(this.hostConnection, frame);
|
|
927
|
+
}
|
|
928
|
+
toPhones(frame) {
|
|
929
|
+
const data = encodeFrame(frame);
|
|
930
|
+
for (const seat of this.seats.values())
|
|
931
|
+
if (seat.connection !== null) this.send(seat.connection, data);
|
|
932
|
+
}
|
|
933
|
+
send(connection, frame) {
|
|
934
|
+
const data = typeof frame === "string" || frame instanceof Uint8Array ? frame : encodeFrame(frame);
|
|
935
|
+
this.effects.push({ send: connection, data });
|
|
936
|
+
}
|
|
937
|
+
closeConnection(connection, reason) {
|
|
938
|
+
this.effects.push({ close: connection, reason });
|
|
939
|
+
}
|
|
940
|
+
fact(at, event) {
|
|
941
|
+
this.effects.push({
|
|
942
|
+
fact: {
|
|
943
|
+
at,
|
|
944
|
+
code: this.code,
|
|
945
|
+
instance: this.instance,
|
|
946
|
+
labels: this.labels,
|
|
947
|
+
...event
|
|
948
|
+
}
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
record() {
|
|
952
|
+
return {
|
|
953
|
+
code: this.code,
|
|
954
|
+
instance: this.instance,
|
|
955
|
+
hostKey: this.hostKey,
|
|
956
|
+
limits: this.limits,
|
|
957
|
+
labels: this.labels,
|
|
958
|
+
activity: this.activity,
|
|
959
|
+
activityChangeable: this.activityChangeable,
|
|
960
|
+
openedAt: this.openedAt,
|
|
961
|
+
seatsWanted: this.seatsWanted,
|
|
962
|
+
locked: this.locked,
|
|
963
|
+
nextSeatNumber: this.nextSeatNumber,
|
|
964
|
+
hostConnection: this.hostConnection,
|
|
965
|
+
hostAwayUntil: this.hostAwayUntil
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
savedSeat(seat) {
|
|
969
|
+
return { ...seat };
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
|
|
973
|
+
// src/room-host/memory-room-host.ts
|
|
974
|
+
import {
|
|
975
|
+
encodeFrame as encodeFrame2,
|
|
976
|
+
joinHostInputFrames,
|
|
977
|
+
parseHostHello as parseHostHello2,
|
|
978
|
+
PING_FRAME as PING_FRAME2,
|
|
979
|
+
PONG_FRAME as PONG_FRAME2,
|
|
980
|
+
ROOM_CODE_ALPHABET,
|
|
981
|
+
ROOM_CODE_LENGTH,
|
|
982
|
+
roomCloseCodes
|
|
983
|
+
} from "@air-jam/sdk/room-protocol";
|
|
984
|
+
import { systemRoomClock } from "@air-jam/sdk/room-session";
|
|
985
|
+
var ADMISSION_BUFFER_FRAMES = 16;
|
|
986
|
+
var HELLO_DEADLINE_MS = 15e3;
|
|
987
|
+
var randomCode = () => Array.from(
|
|
988
|
+
crypto.getRandomValues(new Uint8Array(ROOM_CODE_LENGTH)),
|
|
989
|
+
(byte) => ROOM_CODE_ALPHABET[byte % ROOM_CODE_ALPHABET.length]
|
|
990
|
+
).join("");
|
|
991
|
+
var MemoryRoomHost = class {
|
|
992
|
+
constructor(options) {
|
|
993
|
+
this.options = options;
|
|
994
|
+
this.clock = options.clock ?? systemRoomClock;
|
|
995
|
+
this.afterTurn = options.afterTurn ?? queueMicrotask;
|
|
996
|
+
}
|
|
997
|
+
rooms = /* @__PURE__ */ new Map();
|
|
998
|
+
connections = /* @__PURE__ */ new Map();
|
|
999
|
+
pendingInput = /* @__PURE__ */ new Map();
|
|
1000
|
+
flushScheduled = false;
|
|
1001
|
+
nextConnection = 1;
|
|
1002
|
+
stopped = false;
|
|
1003
|
+
clock;
|
|
1004
|
+
afterTurn;
|
|
1005
|
+
accept(address, origin, transport) {
|
|
1006
|
+
const accepted = {
|
|
1007
|
+
id: `c${this.nextConnection}`,
|
|
1008
|
+
address,
|
|
1009
|
+
origin,
|
|
1010
|
+
transport,
|
|
1011
|
+
stage: "hello",
|
|
1012
|
+
room: null,
|
|
1013
|
+
buffered: [],
|
|
1014
|
+
cancelGateRetry: null,
|
|
1015
|
+
cancelHelloDeadline: null
|
|
1016
|
+
};
|
|
1017
|
+
this.nextConnection += 1;
|
|
1018
|
+
this.connections.set(accepted.id, accepted);
|
|
1019
|
+
if (this.stopped) this.closeConnection(accepted, "restarting");
|
|
1020
|
+
else
|
|
1021
|
+
accepted.cancelHelloDeadline = this.clock.at(
|
|
1022
|
+
this.clock.now() + HELLO_DEADLINE_MS,
|
|
1023
|
+
() => {
|
|
1024
|
+
accepted.cancelHelloDeadline = null;
|
|
1025
|
+
if (accepted.stage === "hello")
|
|
1026
|
+
this.closeConnection(accepted, "try-later");
|
|
1027
|
+
}
|
|
1028
|
+
);
|
|
1029
|
+
return {
|
|
1030
|
+
receive: (data) => this.receive(accepted, data),
|
|
1031
|
+
closed: () => this.closed(accepted)
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
/** Stops every room as the server goes down; its devices are told to come back. */
|
|
1035
|
+
stop() {
|
|
1036
|
+
this.stopped = true;
|
|
1037
|
+
for (const hosted of [...this.rooms.values()])
|
|
1038
|
+
this.call(hosted, (room, now) => room.stop("restarting", now));
|
|
1039
|
+
for (const accepted of [...this.connections.values()])
|
|
1040
|
+
if (accepted.stage !== "bound")
|
|
1041
|
+
this.closeConnection(accepted, "restarting");
|
|
1042
|
+
}
|
|
1043
|
+
describe() {
|
|
1044
|
+
return [...this.rooms.values()].map((hosted) => hosted.room.describe());
|
|
1045
|
+
}
|
|
1046
|
+
receive(accepted, data) {
|
|
1047
|
+
if (data === PING_FRAME2) return accepted.transport.send(PONG_FRAME2);
|
|
1048
|
+
switch (accepted.stage) {
|
|
1049
|
+
case "closed":
|
|
1050
|
+
return;
|
|
1051
|
+
case "bound": {
|
|
1052
|
+
const hosted = accepted.room;
|
|
1053
|
+
if (!hosted) throw new Error(`Connection ${accepted.id} has no room.`);
|
|
1054
|
+
return this.call(
|
|
1055
|
+
hosted,
|
|
1056
|
+
(room, now) => room.receive(accepted.id, data, now)
|
|
1057
|
+
);
|
|
1058
|
+
}
|
|
1059
|
+
case "admitting":
|
|
1060
|
+
if (accepted.buffered.length >= ADMISSION_BUFFER_FRAMES)
|
|
1061
|
+
return this.closeConnection(accepted, "limits-broken");
|
|
1062
|
+
accepted.buffered.push(data);
|
|
1063
|
+
return;
|
|
1064
|
+
case "hello":
|
|
1065
|
+
if (typeof data !== "string")
|
|
1066
|
+
return this.closeConnection(accepted, "unsupported-version");
|
|
1067
|
+
return this.hello(accepted, data);
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
hello(accepted, hello) {
|
|
1071
|
+
accepted.cancelHelloDeadline?.();
|
|
1072
|
+
accepted.cancelHelloDeadline = null;
|
|
1073
|
+
const { address } = accepted;
|
|
1074
|
+
const existing = address.code === null ? void 0 : this.rooms.get(address.code);
|
|
1075
|
+
if (existing) return this.bind(accepted, existing, hello);
|
|
1076
|
+
if (address.role === "phone")
|
|
1077
|
+
return this.closeConnection(accepted, "not-found");
|
|
1078
|
+
const frame = parseHostHello2(hello);
|
|
1079
|
+
if (!frame) return this.closeConnection(accepted, "unsupported-version");
|
|
1080
|
+
if (frame.instance !== void 0 || address.code !== null && !this.options.codesMayBeAsked)
|
|
1081
|
+
return this.closeConnection(accepted, "not-found");
|
|
1082
|
+
accepted.stage = "admitting";
|
|
1083
|
+
void this.admit(accepted, frame, hello);
|
|
1084
|
+
}
|
|
1085
|
+
async admit(accepted, frame, hello) {
|
|
1086
|
+
let decision;
|
|
1087
|
+
try {
|
|
1088
|
+
decision = await this.options.gate.admit({
|
|
1089
|
+
hello: frame,
|
|
1090
|
+
origin: accepted.origin
|
|
1091
|
+
});
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
this.options.onGateError?.(error);
|
|
1094
|
+
return this.closeConnection(accepted, "try-later");
|
|
1095
|
+
}
|
|
1096
|
+
if (accepted.stage !== "admitting") return;
|
|
1097
|
+
if (this.stopped) return this.closeConnection(accepted, "restarting");
|
|
1098
|
+
if (decision.outcome === "refuse")
|
|
1099
|
+
return this.closeConnection(accepted, decision.reason);
|
|
1100
|
+
if (decision.outcome === "wait") {
|
|
1101
|
+
accepted.transport.send(
|
|
1102
|
+
encodeFrame2({ type: "wait", position: decision.position })
|
|
1103
|
+
);
|
|
1104
|
+
accepted.cancelGateRetry = this.clock.at(
|
|
1105
|
+
this.clock.now() + (this.options.gateRetryMs ?? 2e3),
|
|
1106
|
+
() => {
|
|
1107
|
+
accepted.cancelGateRetry = null;
|
|
1108
|
+
void this.admit(accepted, frame, hello);
|
|
1109
|
+
}
|
|
1110
|
+
);
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
const code = accepted.address.code ?? this.freeCode();
|
|
1114
|
+
const existing = this.rooms.get(code);
|
|
1115
|
+
if (existing) return this.bind(accepted, existing, hello);
|
|
1116
|
+
const opened = Room.open(
|
|
1117
|
+
{
|
|
1118
|
+
code,
|
|
1119
|
+
instance: crypto.randomUUID(),
|
|
1120
|
+
hostKey: frame.key,
|
|
1121
|
+
limits: decision.limits,
|
|
1122
|
+
labels: decision.labels,
|
|
1123
|
+
activity: decision.activity,
|
|
1124
|
+
activityChangeable: decision.activityChangeable
|
|
1125
|
+
},
|
|
1126
|
+
this.clock.now()
|
|
1127
|
+
);
|
|
1128
|
+
const hosted = {
|
|
1129
|
+
code,
|
|
1130
|
+
room: opened.room,
|
|
1131
|
+
wakeAt: null,
|
|
1132
|
+
cancelWake: null
|
|
1133
|
+
};
|
|
1134
|
+
this.rooms.set(code, hosted);
|
|
1135
|
+
this.apply(hosted, opened.effects);
|
|
1136
|
+
this.bind(accepted, hosted, hello);
|
|
1137
|
+
}
|
|
1138
|
+
bind(accepted, hosted, hello) {
|
|
1139
|
+
accepted.stage = "bound";
|
|
1140
|
+
accepted.room = hosted;
|
|
1141
|
+
this.call(
|
|
1142
|
+
hosted,
|
|
1143
|
+
(room, now) => room.connect(accepted.id, accepted.address.role, hello, now)
|
|
1144
|
+
);
|
|
1145
|
+
for (const data of accepted.buffered.splice(0))
|
|
1146
|
+
this.receive(accepted, data);
|
|
1147
|
+
}
|
|
1148
|
+
closed(accepted) {
|
|
1149
|
+
const stage = accepted.stage;
|
|
1150
|
+
if (stage === "closed") return;
|
|
1151
|
+
this.forget(accepted);
|
|
1152
|
+
const hosted = accepted.room;
|
|
1153
|
+
if (stage === "bound" && hosted)
|
|
1154
|
+
this.call(hosted, (room, now) => room.disconnect(accepted.id, now));
|
|
1155
|
+
}
|
|
1156
|
+
call(hosted, work) {
|
|
1157
|
+
this.apply(hosted, work(hosted.room, this.clock.now()));
|
|
1158
|
+
this.scheduleWake(hosted);
|
|
1159
|
+
}
|
|
1160
|
+
apply(hosted, effects) {
|
|
1161
|
+
for (const effect of effects) {
|
|
1162
|
+
if ("fact" in effect) {
|
|
1163
|
+
this.options.onFact?.(effect.fact);
|
|
1164
|
+
if (effect.fact.kind === "closed") this.retire(hosted);
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
const target = "send" in effect ? this.connections.get(effect.send) : this.connections.get(effect.close);
|
|
1168
|
+
if (!target) continue;
|
|
1169
|
+
if ("close" in effect) this.closeConnection(target, effect.reason);
|
|
1170
|
+
else if (effect.data instanceof Uint8Array)
|
|
1171
|
+
this.queueInput(target, effect.data);
|
|
1172
|
+
else {
|
|
1173
|
+
this.flushInput(target);
|
|
1174
|
+
target.transport.send(effect.data);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
scheduleWake(hosted) {
|
|
1179
|
+
const next = this.rooms.get(hosted.code) === hosted ? hosted.room.nextWake() : null;
|
|
1180
|
+
if (next === hosted.wakeAt) return;
|
|
1181
|
+
hosted.cancelWake?.();
|
|
1182
|
+
hosted.cancelWake = null;
|
|
1183
|
+
hosted.wakeAt = next;
|
|
1184
|
+
if (next === null) return;
|
|
1185
|
+
hosted.cancelWake = this.clock.at(next, () => {
|
|
1186
|
+
hosted.cancelWake = null;
|
|
1187
|
+
hosted.wakeAt = null;
|
|
1188
|
+
this.call(hosted, (room, now) => room.wake(now));
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
retire(hosted) {
|
|
1192
|
+
if (this.rooms.get(hosted.code) === hosted) this.rooms.delete(hosted.code);
|
|
1193
|
+
hosted.cancelWake?.();
|
|
1194
|
+
hosted.cancelWake = null;
|
|
1195
|
+
}
|
|
1196
|
+
queueInput(target, frame) {
|
|
1197
|
+
const queued = this.pendingInput.get(target.id);
|
|
1198
|
+
if (queued) queued.push(frame);
|
|
1199
|
+
else this.pendingInput.set(target.id, [frame]);
|
|
1200
|
+
if (this.flushScheduled) return;
|
|
1201
|
+
this.flushScheduled = true;
|
|
1202
|
+
this.afterTurn(() => {
|
|
1203
|
+
this.flushScheduled = false;
|
|
1204
|
+
for (const id of [...this.pendingInput.keys()]) {
|
|
1205
|
+
const connection = this.connections.get(id);
|
|
1206
|
+
if (connection) this.flushInput(connection);
|
|
1207
|
+
}
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
/** Sends what is queued for a host before anything that follows it, keeping order. */
|
|
1211
|
+
flushInput(target) {
|
|
1212
|
+
const frames = this.pendingInput.get(target.id);
|
|
1213
|
+
if (!frames) return;
|
|
1214
|
+
this.pendingInput.delete(target.id);
|
|
1215
|
+
target.transport.send(
|
|
1216
|
+
frames.length === 1 && frames[0] ? frames[0] : joinHostInputFrames(frames)
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
closeConnection(accepted, reason) {
|
|
1220
|
+
if (accepted.stage === "closed") return;
|
|
1221
|
+
this.forget(accepted);
|
|
1222
|
+
accepted.transport.close(roomCloseCodes[reason].code);
|
|
1223
|
+
}
|
|
1224
|
+
forget(accepted) {
|
|
1225
|
+
accepted.stage = "closed";
|
|
1226
|
+
accepted.cancelGateRetry?.();
|
|
1227
|
+
accepted.cancelGateRetry = null;
|
|
1228
|
+
accepted.cancelHelloDeadline?.();
|
|
1229
|
+
accepted.cancelHelloDeadline = null;
|
|
1230
|
+
this.connections.delete(accepted.id);
|
|
1231
|
+
this.pendingInput.delete(accepted.id);
|
|
1232
|
+
}
|
|
1233
|
+
freeCode() {
|
|
1234
|
+
for (; ; ) {
|
|
1235
|
+
const code = randomCode();
|
|
1236
|
+
if (!this.rooms.has(code)) return code;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
|
|
1241
|
+
// src/room/gate.ts
|
|
1242
|
+
import {
|
|
1243
|
+
DEFAULT_ROOM_LIMITS
|
|
1244
|
+
} from "@air-jam/sdk/room-protocol";
|
|
1245
|
+
var openDecision = (limits, activityChangeable) => ({
|
|
1246
|
+
outcome: "open",
|
|
1247
|
+
limits,
|
|
1248
|
+
labels: {},
|
|
1249
|
+
activity: null,
|
|
1250
|
+
activityChangeable
|
|
1251
|
+
});
|
|
1252
|
+
var createOpenRoomGate = (limits = DEFAULT_ROOM_LIMITS) => ({
|
|
1253
|
+
admit: () => openDecision(limits, true)
|
|
1254
|
+
});
|
|
1255
|
+
var createMasterKeyRoomGate = (masterKey, limits = DEFAULT_ROOM_LIMITS) => {
|
|
1256
|
+
if (masterKey.length === 0)
|
|
1257
|
+
throw new Error("A master key gate needs a master key.");
|
|
1258
|
+
return {
|
|
1259
|
+
admit: ({ hello }) => hello.credential !== void 0 && sameSecret(hello.credential, masterKey) ? openDecision(limits, false) : { outcome: "refuse", reason: "unauthorised" }
|
|
1260
|
+
};
|
|
1261
|
+
};
|
|
1262
|
+
|
|
1263
|
+
export {
|
|
1264
|
+
ROOM_SAVE_SCHEMA,
|
|
1265
|
+
Room,
|
|
1266
|
+
HELLO_DEADLINE_MS,
|
|
1267
|
+
MemoryRoomHost,
|
|
1268
|
+
createOpenRoomGate,
|
|
1269
|
+
createMasterKeyRoomGate
|
|
1270
|
+
};
|
|
1271
|
+
//# sourceMappingURL=chunk-64G5AWIQ.js.map
|