@air-jam/server 0.9.2 → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/air-jam-server.mjs +43 -20
- package/dist/.tsbuildinfo +1 -0
- package/dist/chunk-2BHF5ZCS.js +38 -0
- package/dist/chunk-2BHF5ZCS.js.map +1 -0
- package/dist/{chunk-5ZVGSYXC.js → chunk-5YSBR6YK.js} +1 -46
- 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 +31 -112
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +31 -0
- package/dist/index.js +15 -5972
- 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 +42 -29
- package/dist/chunk-5ZVGSYXC.js.map +0 -1
- package/dist/chunk-RM7AMBDY.js +0 -831
- package/dist/chunk-RM7AMBDY.js.map +0 -1
- package/dist/game-dev-D3TEAHOD.js +0 -422
- package/dist/game-dev-D3TEAHOD.js.map +0 -1
- package/dist/local-dev-state-QT7H5GUA.js +0 -270
- package/dist/local-dev-state-QT7H5GUA.js.map +0 -1
- package/dist/secure-dev-HMOGLYVC.js +0 -39
- package/dist/topology-PM3PI753.js +0 -140
- package/dist/topology-PM3PI753.js.map +0 -1
- package/src/project-cli/vite-config.d.mts +0 -17
- package/src/project-cli/vite-config.mjs +0 -121
- package/src/project-cli/vite-https.d.mts +0 -14
- package/src/project-cli/vite-https.mjs +0 -39
- /package/dist/{secure-dev-HMOGLYVC.js.map → process-lifecycle-A55YCNJN.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/room/saved-room.ts","../src/room/room.ts","../src/room/channel-copies.ts","../src/room/connection-budget.ts","../src/room/secrets.ts","../src/room-host/memory-room-host.ts","../src/room/gate.ts"],"sourcesContent":["import type { RoomLimits, SeatId, SeatKind } from \"@air-jam/sdk/room-protocol\";\nimport type { SavedChannel } from \"./channel-copies.js\";\nimport type { RoomLabels } from \"./facts.js\";\n\n/**\n * A room's durable state. Saved state outlives a deploy, so a newer release\n * must read what an older one wrote: raise the schema with every change and\n * migrate older ones when restoring.\n */\nexport const ROOM_SAVE_SCHEMA = 1;\n\n/** Chosen by the host that holds the connection; opaque to the room. */\nexport type ConnectionId = string;\n\nexport interface SavedRoomRecord {\n readonly code: string;\n readonly instance: string;\n readonly hostKey: string;\n readonly limits: RoomLimits;\n readonly labels: RoomLabels;\n readonly activity: string | null;\n readonly activityChangeable: boolean;\n readonly openedAt: number;\n readonly seatsWanted: number;\n readonly locked: boolean;\n readonly nextSeatNumber: number;\n readonly hostConnection: ConnectionId | null;\n /** When the room closes unless its host returns; null while the host is in. */\n readonly hostAwayUntil: number | null;\n}\n\nexport interface SavedSeat {\n readonly id: SeatId;\n readonly key: string;\n readonly kind: SeatKind;\n /** The player's own label, shown whenever no local seat label covers it. */\n readonly label: string;\n readonly localSeatLabel?: string;\n readonly avatarId?: string;\n readonly color: string;\n /** The page the seat's phone last joined from. */\n readonly page?: string;\n readonly connection: ConnectionId | null;\n /** When the seat is freed unless its phone returns; null while connected. */\n readonly holdUntil: number | null;\n}\n\nexport interface SavedRoom {\n readonly schema: number;\n readonly room: SavedRoomRecord;\n readonly seats: Readonly<Record<SeatId, SavedSeat>>;\n readonly channels: Readonly<Record<string, SavedChannel>>;\n}\n\n/** The durable slices that changed since the last save; null marks one deleted. */\nexport interface SavedRoomChanges {\n readonly schema: number;\n readonly room?: SavedRoomRecord;\n readonly seats: Readonly<Record<SeatId, SavedSeat | null>>;\n readonly channels: Readonly<Record<string, SavedChannel | null>>;\n}\n","import {\n encodeFrame,\n encodeHostInputFrame,\n INPUT_FRAME_KIND,\n MAXIMUM_SEAT_NUMBER,\n parseHostHello,\n parseHostToRoomFrame,\n parsePhoneHello,\n parsePhoneToRoomFrame,\n PING_FRAME,\n PONG_FRAME,\n roomLimitsSchema,\n seatIdFromNumber,\n utf8ByteLength,\n type HostHello,\n type HostToRoomFrame,\n type PhoneHello,\n type PhoneToRoomFrame,\n type RoomCloseReason,\n type RoomLimits,\n type RoomRole,\n type RoomToHostFrame,\n type RoomToPhoneFrame,\n type SeatId,\n type SeatKind,\n type SeatView,\n} from \"@air-jam/sdk/room-protocol\";\nimport { ChannelCopies } from \"./channel-copies.js\";\nimport { ConnectionBudget, type FrameLane } from \"./connection-budget.js\";\nimport type {\n RoomCloseCause,\n RoomEvent,\n RoomFact,\n RoomLabels,\n SeatLeaveCause,\n} from \"./facts.js\";\nimport {\n ROOM_SAVE_SCHEMA,\n type ConnectionId,\n type SavedRoom,\n type SavedRoomChanges,\n type SavedRoomRecord,\n type SavedSeat,\n} from \"./saved-room.js\";\nimport { sameSecret } from \"./secrets.js\";\n\nexport interface RoomSetup {\n readonly code: string;\n readonly instance: string;\n /** The opening host's key; only it can be the host of this room. */\n readonly hostKey: string;\n readonly limits: RoomLimits;\n readonly labels: RoomLabels;\n /** What is on screen as the room opens, such as the game a hosted grant names. */\n readonly activity: string | null;\n /** Whether the host may change it, as a launcher does when it starts a game. */\n readonly activityChangeable: boolean;\n}\n\nexport type RoomEffect =\n | { readonly send: ConnectionId; readonly data: string | Uint8Array }\n | { readonly close: ConnectionId; readonly reason: RoomCloseReason }\n | { readonly fact: RoomFact };\n\nexport type RoomStopReason = \"operator\" | \"restarting\";\n\nexport interface RoomDescription {\n readonly code: string;\n readonly instance: string;\n readonly labels: RoomLabels;\n readonly openedAt: number;\n readonly closed: boolean;\n readonly activity: string | null;\n readonly limits: RoomLimits;\n readonly seatsWanted: number;\n readonly locked: boolean;\n readonly host: {\n readonly connected: boolean;\n readonly awayUntil: number | null;\n };\n readonly seats: ReadonlyArray<{\n readonly id: SeatId;\n readonly kind: SeatKind;\n readonly label: string;\n readonly connected: boolean;\n readonly holdUntil: number | null;\n }>;\n readonly channels: ReadonlyArray<{\n readonly channel: string;\n readonly revision: number;\n readonly weight: number;\n }>;\n /** Frames handled since this room was opened or restored. */\n readonly counters: Readonly<RoomCounters>;\n}\n\ninterface RoomCounters {\n inputs: number;\n states: number;\n requests: number;\n signals: number;\n /** Frames over their lane's rate; a phone's latest input among them still arrives when the rate allows. */\n overRate: number;\n strikes: number;\n}\n\ninterface Seat {\n readonly id: SeatId;\n readonly key: string;\n readonly kind: SeatKind;\n label: string;\n localSeatLabel?: string;\n avatarId?: string;\n readonly color: string;\n page?: string;\n connection: ConnectionId | null;\n holdUntil: number | null;\n}\n\ntype Connection =\n | { readonly role: \"host\"; readonly budget: ConnectionBudget }\n | {\n readonly role: \"phone\";\n readonly seat: SeatId;\n readonly budget: ConnectionBudget;\n /**\n * Requests sent on this connection that the host has yet to answer; an\n * answer settles only one of these, so a reloaded phone, whose request\n * ids start again, never takes an answer meant for its earlier page.\n * Null for a connection restored from saved state, whose requests the\n * room no longer knows.\n */\n readonly requests: Set<number> | null;\n };\n\n/** Requests a phone may have waiting for the host; past it the oldest answer is no longer expected. */\nconst MAXIMUM_WAITING_REQUESTS = 256;\n\nconst PLAYER_COLORS = [\n \"#38bdf8\",\n \"#a78bfa\",\n \"#f472b6\",\n \"#34d399\",\n \"#fbbf24\",\n \"#60a5fa\",\n \"#c084fc\",\n \"#fb7185\",\n \"#4ade80\",\n \"#f87171\",\n \"#22d3ee\",\n \"#a855f7\",\n \"#ec4899\",\n \"#10b981\",\n \"#f59e0b\",\n \"#3b82f6\",\n] as const;\n\n/**\n * One host, its seats and what flows between them. Bytes and the current time\n * go in; frames to send, connections to close and facts come out. The room\n * never waits, sets a timer, reads a clock or draws a random number: every\n * deadline is a timestamp in its state, and `nextWake` says when the host\n * should call `wake`. Every entry point first applies the deadlines that have\n * passed, so a late wake changes nothing a device can observe.\n */\nexport class Room {\n private readonly seats = new Map<SeatId, Seat>();\n private readonly seatsByKey = new Map<string, SeatId>();\n private readonly connections = new Map<ConnectionId, Connection>();\n private readonly channels: ChannelCopies;\n private readonly counters: RoomCounters = {\n inputs: 0,\n states: 0,\n requests: 0,\n signals: 0,\n overRate: 0,\n strikes: 0,\n };\n /** Each phone's latest input that arrived over its rate, delivered when its rate window ends. */\n private readonly heldInputs = new Map<ConnectionId, Uint8Array>();\n private hostConnection: ConnectionId | null = null;\n private hostAwayUntil: number | null;\n private activity: string | null;\n private seatsWanted: number;\n private locked = false;\n private nextSeatNumber = 1;\n private closed = false;\n private roomChanged = true;\n private readonly changedSeats = new Set<SeatId>();\n private readonly changedChannels = new Set<string>();\n private effects: RoomEffect[] = [];\n\n private constructor(\n private readonly code: string,\n private readonly instance: string,\n private readonly hostKey: string,\n private readonly limits: RoomLimits,\n private readonly labels: RoomLabels,\n private readonly activityChangeable: boolean,\n private readonly openedAt: number,\n activity: string | null,\n ) {\n this.channels = new ChannelCopies(limits);\n this.activity = activity;\n // No player is admitted until the host has said how many its game takes.\n this.seatsWanted = 0;\n this.hostAwayUntil = openedAt + limits.hostGraceMs;\n }\n\n static open(\n setup: RoomSetup,\n now: number,\n ): { room: Room; effects: RoomEffect[] } {\n const room = new Room(\n setup.code,\n setup.instance,\n setup.hostKey,\n roomLimitsSchema.parse(setup.limits),\n setup.labels,\n setup.activityChangeable,\n now,\n setup.activity,\n );\n const effects = room.run(now, () => room.fact(now, { kind: \"opened\" }));\n return { room, effects };\n }\n\n /**\n * Rebuilds a room from its saved state and the connections still open, as\n * a Durable Object does when it wakes. Devices whose connection closed\n * while the room was away are treated as having dropped now. State saved by\n * a newer release cannot be read: every connection is told the server is\n * restarting and there is no room.\n */\n static restore(\n saved: SavedRoom,\n live: readonly ConnectionId[],\n now: number,\n ): { room: Room | null; effects: RoomEffect[] } {\n if (saved.schema > ROOM_SAVE_SCHEMA)\n return {\n room: null,\n effects: live.map((connection) => ({\n close: connection,\n reason: \"restarting\",\n })),\n };\n const record = saved.room;\n const room = new Room(\n record.code,\n record.instance,\n record.hostKey,\n record.limits,\n record.labels,\n record.activityChangeable,\n record.openedAt,\n record.activity,\n );\n room.seatsWanted = record.seatsWanted;\n room.locked = record.locked;\n room.nextSeatNumber = record.nextSeatNumber;\n room.hostAwayUntil = record.hostAwayUntil;\n room.hostConnection = record.hostConnection;\n for (const seat of Object.values(saved.seats)) {\n room.seats.set(seat.id, { ...seat });\n room.seatsByKey.set(seat.key, seat.id);\n }\n for (const channel of Object.values(saved.channels))\n room.channels.restore(channel);\n room.roomChanged = false;\n // Bind what is still open before applying deadlines, so nothing is sent\n // to a connection that closed while the room was away.\n room.reconnect(new Set(live), now);\n room.settle(now);\n // Input held over the rate is not saved, so phones send their controls again.\n if (room.hostConnection !== null)\n room.toPhones({ type: \"host\", present: true });\n return { room, effects: room.effects };\n }\n\n /**\n * A device's first frame. `role` comes from the path it connected to, so\n * the path alone decides who may act as a host.\n */\n connect(\n connection: ConnectionId,\n role: RoomRole,\n hello: string,\n now: number,\n ): RoomEffect[] {\n return this.run(now, () => {\n if (this.connections.has(connection))\n throw new Error(`Connection ${connection} already said hello.`);\n if (this.closed) return this.closeConnection(connection, \"closed\");\n if (utf8ByteLength(hello) > this.limits.frameBytes)\n return this.closeConnection(connection, \"limits-broken\");\n if (role === \"host\") {\n const frame = parseHostHello(hello);\n if (!frame)\n return this.closeConnection(connection, \"unsupported-version\");\n this.connectHost(connection, frame, now);\n } else {\n const frame = parsePhoneHello(hello);\n if (!frame)\n return this.closeConnection(connection, \"unsupported-version\");\n this.connectPhone(connection, frame, now);\n }\n });\n }\n\n receive(\n connection: ConnectionId,\n data: string | Uint8Array,\n now: number,\n ): RoomEffect[] {\n return this.run(now, () => {\n const entry = this.connections.get(connection);\n if (!entry) return;\n if (data === PING_FRAME) {\n if (!entry.budget.spend(\"frame\", now))\n return this.breakLimits(connection, entry, now);\n return this.send(connection, PONG_FRAME);\n }\n if (typeof data === \"string\") {\n if (entry.role === \"host\")\n this.receiveHostText(connection, entry, data, now);\n else this.receivePhoneText(connection, entry, data, now);\n } else if (entry.role === \"phone\") {\n this.receiveInput(connection, entry, data, now);\n } else this.ignore(connection, entry, \"unknown\", \"frame\", now);\n });\n }\n\n disconnect(connection: ConnectionId, now: number): RoomEffect[] {\n return this.run(now, () => {\n const entry = this.connections.get(connection);\n if (!entry) return;\n this.connections.delete(connection);\n this.release(entry, now);\n });\n }\n\n wake(now: number): RoomEffect[] {\n return this.run(now, () => {});\n }\n\n stop(reason: RoomStopReason, now: number): RoomEffect[] {\n return this.run(now, () => {\n if (!this.closed) this.closeRoom(reason, now);\n });\n }\n\n /** The earliest moment something is due, or null once the room is closed. */\n nextWake(): number | null {\n if (this.closed) return null;\n let earliest = this.openedAt + this.limits.maximumAgeMs;\n if (this.hostAwayUntil !== null)\n earliest = Math.min(earliest, this.hostAwayUntil);\n for (const seat of this.seats.values())\n if (seat.holdUntil !== null)\n earliest = Math.min(earliest, seat.holdUntil);\n for (const connection of this.heldInputs.keys()) {\n const entry = this.connections.get(connection);\n if (entry) earliest = Math.min(earliest, entry.budget.windowEndsAt);\n }\n const ask = this.hostConnection === null ? null : this.channels.nextAsk();\n if (ask !== null) earliest = Math.min(earliest, ask);\n return earliest;\n }\n\n save(): SavedRoomChanges | null {\n if (\n !this.roomChanged &&\n this.changedSeats.size === 0 &&\n this.changedChannels.size === 0\n )\n return null;\n const changes: SavedRoomChanges = {\n schema: ROOM_SAVE_SCHEMA,\n ...(this.roomChanged ? { room: this.record() } : {}),\n seats: Object.fromEntries(\n [...this.changedSeats].map((id) => {\n const seat = this.seats.get(id);\n return [id, seat ? this.savedSeat(seat) : null];\n }),\n ),\n channels: Object.fromEntries(\n [...this.changedChannels].map((channel) => [\n channel,\n this.channels.saved(channel),\n ]),\n ),\n };\n this.roomChanged = false;\n this.changedSeats.clear();\n this.changedChannels.clear();\n return changes;\n }\n\n describe(): RoomDescription {\n return {\n code: this.code,\n instance: this.instance,\n labels: this.labels,\n openedAt: this.openedAt,\n closed: this.closed,\n activity: this.activity,\n limits: this.limits,\n seatsWanted: this.seatsWanted,\n locked: this.locked,\n host: {\n connected: this.hostConnection !== null,\n awayUntil: this.hostAwayUntil,\n },\n seats: [...this.seats.values()].map((seat) => ({\n id: seat.id,\n kind: seat.kind,\n label: seat.localSeatLabel ?? seat.label,\n connected: seat.connection !== null,\n holdUntil: seat.holdUntil,\n })),\n channels: this.channels.describe(),\n counters: { ...this.counters },\n };\n }\n\n private run(now: number, work: () => void): RoomEffect[] {\n this.effects = [];\n this.settle(now);\n work();\n // A deadline of zero length, such as an agent seat's hold, is due at once.\n this.settle(now);\n return this.effects;\n }\n\n private settle(now: number): void {\n if (this.closed) return;\n // A late wake closes for whichever deadline passed first.\n const expiresAt = this.openedAt + this.limits.maximumAgeMs;\n const hostGoneAt = this.hostAwayUntil ?? Number.POSITIVE_INFINITY;\n if (now >= Math.min(expiresAt, hostGoneAt))\n return hostGoneAt < expiresAt\n ? this.closeRoom(\"host-gone\", hostGoneAt)\n : this.closeRoom(\"expired\", expiresAt);\n for (const seat of [...this.seats.values()])\n if (seat.holdUntil !== null && now >= seat.holdUntil)\n this.freeSeat(seat, \"dropped\", seat.holdUntil);\n for (const [connection, frame] of [...this.heldInputs]) {\n const entry = this.connections.get(connection);\n if (entry?.role !== \"phone\") {\n this.heldInputs.delete(connection);\n continue;\n }\n if (now < entry.budget.windowEndsAt) continue;\n this.heldInputs.delete(connection);\n if (entry.budget.fits(\"input\", now)) this.forwardInput(entry, frame);\n }\n if (this.hostConnection !== null)\n for (const channel of this.channels.due(now))\n this.send(this.hostConnection, { type: \"need\", channel });\n }\n\n private reconnect(live: ReadonlySet<ConnectionId>, now: number): void {\n const hostDropped =\n this.hostConnection !== null && !live.has(this.hostConnection);\n if (hostDropped) this.hostConnection = null;\n const droppedSeats: Seat[] = [];\n for (const seat of this.seats.values())\n if (seat.connection !== null && !live.has(seat.connection)) {\n seat.connection = null;\n droppedSeats.push(seat);\n }\n if (this.hostConnection !== null)\n this.connections.set(this.hostConnection, {\n role: \"host\",\n budget: new ConnectionBudget(this.limits, now),\n });\n for (const seat of this.seats.values())\n if (seat.connection !== null)\n this.connections.set(seat.connection, {\n role: \"phone\",\n seat: seat.id,\n budget: new ConnectionBudget(this.limits, now),\n requests: null,\n });\n if (hostDropped) this.hostLeft(now);\n for (const seat of droppedSeats) this.seatLeft(seat, now);\n }\n\n private connectHost(\n connection: ConnectionId,\n hello: HostHello,\n now: number,\n ): void {\n if (hello.instance !== undefined && hello.instance !== this.instance)\n return this.closeConnection(connection, \"not-found\");\n if (!sameSecret(hello.key, this.hostKey))\n return this.closeConnection(connection, \"unauthorised\");\n if (this.hostConnection !== null) {\n this.connections.delete(this.hostConnection);\n this.closeConnection(this.hostConnection, \"replaced\");\n }\n this.hostConnection = connection;\n this.hostAwayUntil = null;\n this.connections.set(connection, {\n role: \"host\",\n budget: new ConnectionBudget(this.limits, now),\n });\n this.seatsWanted = Math.min(hello.seats, this.limits.seats);\n this.roomChanged = true;\n this.send(connection, {\n type: \"welcome\",\n code: this.code,\n instance: this.instance,\n seats: this.seatViews(),\n channels: this.channels.forHost(),\n limits: this.limits,\n features: [],\n seatsWanted: this.seatsWanted,\n locked: this.locked,\n activity: this.activity,\n });\n // Phones send their controls again to every new host connection, even\n // one that replaced a connection the room still thought was open.\n this.toPhones({ type: \"host\", present: true });\n }\n\n private connectPhone(\n connection: ConnectionId,\n hello: PhoneHello,\n now: number,\n ): void {\n if (hello.instance !== undefined && hello.instance !== this.instance)\n return this.closeConnection(connection, \"not-found\");\n const existingId = this.seatsByKey.get(hello.key);\n let seat =\n existingId === undefined ? undefined : this.seats.get(existingId);\n let resumed: boolean | null = null;\n let inputBaseline = false;\n if (seat) {\n inputBaseline = hello.page !== seat.page;\n if (seat.connection !== null) {\n this.connections.delete(seat.connection);\n this.closeConnection(seat.connection, \"replaced\");\n } else resumed = true;\n const profile = hello.profile ?? {};\n if (profile.label !== undefined) seat.label = profile.label;\n if (profile.avatarId !== undefined) seat.avatarId = profile.avatarId;\n seat.localSeatLabel = profile.localSeatLabel;\n } else {\n // A resume proves a seat that no longer exists; it never makes one.\n if (hello.instance !== undefined)\n return this.closeConnection(connection, \"not-found\");\n if (\n this.locked ||\n this.seats.size >= this.seatsWanted ||\n this.nextSeatNumber > MAXIMUM_SEAT_NUMBER\n )\n return this.closeConnection(connection, \"full\");\n seat = this.createSeat(hello);\n resumed = false;\n }\n seat.page = hello.page;\n seat.connection = connection;\n seat.holdUntil = null;\n this.changedSeats.add(seat.id);\n this.connections.set(connection, {\n role: \"phone\",\n seat: seat.id,\n budget: new ConnectionBudget(this.limits, now),\n requests: new Set(),\n });\n this.send(connection, {\n type: \"welcome\",\n code: this.code,\n instance: this.instance,\n seat: seat.id,\n seats: this.seatViews(),\n channels: this.channels.forSeat(seat.id),\n limits: this.limits,\n features: [],\n host: this.hostConnection !== null,\n });\n this.announceSeat(seat, seat.id, inputBaseline);\n if (resumed !== null)\n this.fact(now, {\n kind: \"seat-joined\",\n seat: seat.id,\n seatKind: seat.kind,\n resumed,\n });\n }\n\n private createSeat(hello: PhoneHello): Seat {\n const seatNumber = this.nextSeatNumber;\n this.nextSeatNumber += 1;\n this.roomChanged = true;\n const colorsInUse = new Set(\n [...this.seats.values()].map((seat) => seat.color),\n );\n const seat: Seat = {\n id: seatIdFromNumber(seatNumber),\n key: hello.key,\n kind: hello.kind,\n label: hello.profile?.label ?? `Player ${seatNumber}`,\n localSeatLabel: hello.profile?.localSeatLabel,\n avatarId: hello.profile?.avatarId,\n color:\n PLAYER_COLORS.find((color) => !colorsInUse.has(color)) ??\n PLAYER_COLORS[(seatNumber - 1) % PLAYER_COLORS.length] ??\n PLAYER_COLORS[0],\n connection: null,\n holdUntil: null,\n };\n this.seats.set(seat.id, seat);\n this.seatsByKey.set(seat.key, seat.id);\n return seat;\n }\n\n private receiveHostText(\n connection: ConnectionId,\n entry: Connection,\n text: string,\n now: number,\n ): void {\n const bytes = utf8ByteLength(text);\n if (bytes > this.limits.stateBytes)\n return this.breakLimits(connection, entry, now);\n const parsed = parseHostToRoomFrame(text);\n if (parsed.status !== \"frame\")\n return this.ignore(connection, entry, parsed.status, \"frame\", now);\n const frame = parsed.frame;\n if (frame.type !== \"state\" && bytes > this.limits.frameBytes)\n return this.breakLimits(connection, entry, now);\n const admission = entry.budget.admit(\n frame.type === \"state\" ? \"state\" : \"frame\",\n now,\n );\n if (admission === \"flooded\")\n return this.breakLimits(connection, entry, now);\n if (admission === \"over-rate\") {\n this.counters.overRate += 1;\n // A dropped state frame leaves the room's copy behind the host's.\n if (frame.type === \"state\")\n this.channels.fellBehind(frame.channel, entry.budget.windowEndsAt);\n return;\n }\n this.handleHostFrame(connection, entry, frame, now);\n }\n\n private handleHostFrame(\n connection: ConnectionId,\n entry: Connection,\n frame: HostToRoomFrame,\n now: number,\n ): void {\n switch (frame.type) {\n case \"state\": {\n this.counters.states += 1;\n const outcome = this.channels.receive(frame, now);\n if (outcome.kind === \"applied\") {\n this.changedChannels.add(outcome.channel);\n for (const seat of this.seats.values())\n if (seat.connection !== null)\n this.send(seat.connection, outcome.frameFor(seat.id));\n } else if (outcome.kind === \"need\") {\n this.send(connection, { type: \"need\", channel: outcome.channel });\n } else if (outcome.kind !== \"waiting\") {\n this.breakLimits(connection, entry, now);\n }\n return;\n }\n case \"response\": {\n const asker = this.seats.get(frame.seat)?.connection ?? null;\n const phone = asker === null ? undefined : this.connections.get(asker);\n if (\n asker !== null &&\n phone?.role === \"phone\" &&\n (phone.requests === null || phone.requests.delete(frame.id))\n )\n this.send(asker, {\n type: \"response\",\n id: frame.id,\n result: frame.result,\n });\n return;\n }\n case \"signal\": {\n this.counters.signals += 1;\n const signal = {\n type: \"signal\",\n kind: frame.kind,\n payload: frame.payload,\n } as const;\n if (frame.seat === undefined) return this.toPhones(signal);\n const seat = this.seats.get(frame.seat);\n if (seat?.connection) this.send(seat.connection, signal);\n return;\n }\n case \"room\":\n if (frame.seats !== undefined)\n this.seatsWanted = Math.min(frame.seats, this.limits.seats);\n if (frame.locked !== undefined) this.locked = frame.locked;\n this.roomChanged = true;\n return;\n case \"remove\": {\n const seat = this.seats.get(frame.seat);\n if (!seat) return;\n if (seat.connection !== null) {\n this.connections.delete(seat.connection);\n this.closeConnection(seat.connection, \"removed\");\n }\n return this.freeSeat(seat, \"removed\", now);\n }\n case \"drop\":\n if (!this.channels.drop(frame.channel)) return;\n this.changedChannels.add(frame.channel);\n return this.toPhones({ type: \"drop\", channel: frame.channel });\n case \"activity\": {\n if (!this.activityChangeable)\n return this.strike(connection, entry, now);\n if (frame.activity === this.activity) return;\n const previous = this.activity;\n this.activity = frame.activity;\n this.roomChanged = true;\n return this.fact(now, {\n kind: \"activity\",\n activity: frame.activity,\n previous,\n });\n }\n case \"end\":\n return this.closeRoom(\"ended\", now);\n }\n }\n\n private receivePhoneText(\n connection: ConnectionId,\n entry: Extract<Connection, { role: \"phone\" }>,\n text: string,\n now: number,\n ): void {\n if (utf8ByteLength(text) > this.limits.frameBytes)\n return this.breakLimits(connection, entry, now);\n const parsed = parsePhoneToRoomFrame(text);\n if (parsed.status !== \"frame\")\n return this.ignore(connection, entry, parsed.status, \"frame\", now);\n const admission = entry.budget.admit(\"frame\", now);\n if (admission === \"flooded\")\n return this.breakLimits(connection, entry, now);\n if (admission === \"over-rate\") {\n this.counters.overRate += 1;\n return;\n }\n this.handlePhoneFrame(connection, entry, parsed.frame, now);\n }\n\n private handlePhoneFrame(\n connection: ConnectionId,\n entry: Extract<Connection, { role: \"phone\" }>,\n frame: PhoneToRoomFrame,\n now: number,\n ): void {\n const seatId = entry.seat;\n const seat = this.seats.get(seatId);\n if (!seat) throw new Error(`Connection ${connection} has no seat.`);\n switch (frame.type) {\n case \"request\":\n this.counters.requests += 1;\n if (this.hostConnection === null)\n return this.send(connection, {\n type: \"response\",\n id: frame.id,\n refused: \"host-away\",\n });\n if (entry.requests) {\n const oldest = entry.requests.values().next();\n if (entry.requests.size >= MAXIMUM_WAITING_REQUESTS && !oldest.done)\n entry.requests.delete(oldest.value);\n entry.requests.add(frame.id);\n }\n return this.send(this.hostConnection, {\n type: \"request\",\n seat: seatId,\n id: frame.id,\n channel: frame.channel,\n name: frame.name,\n payload: frame.payload,\n });\n case \"profile\":\n if (frame.label !== undefined) seat.label = frame.label;\n if (frame.avatarId !== undefined) seat.avatarId = frame.avatarId;\n this.changedSeats.add(seatId);\n return this.announceSeat(seat, null);\n case \"leave\":\n this.connections.delete(connection);\n this.closeConnection(connection, \"left\");\n return this.freeSeat(seat, \"left\", now);\n case \"baseline\":\n return this.toHost({\n type: \"seat\",\n seat: this.seatView(seat),\n inputBaseline: true,\n });\n }\n }\n\n private receiveInput(\n connection: ConnectionId,\n entry: Extract<Connection, { role: \"phone\" }>,\n frame: Uint8Array,\n now: number,\n ): void {\n if (frame[0] !== INPUT_FRAME_KIND)\n return this.ignore(connection, entry, \"unknown\", \"input\", now);\n if (frame.byteLength - 1 > this.limits.inputBytes)\n return this.breakLimits(connection, entry, now);\n const admission = entry.budget.admit(\"input\", now);\n if (admission === \"flooded\")\n return this.breakLimits(connection, entry, now);\n if (admission === \"over-rate\") {\n this.counters.overRate += 1;\n this.heldInputs.set(connection, frame);\n return;\n }\n this.heldInputs.delete(connection);\n this.forwardInput(entry, frame);\n }\n\n private forwardInput(\n entry: Extract<Connection, { role: \"phone\" }>,\n frame: Uint8Array,\n ): void {\n if (this.hostConnection === null) return;\n this.counters.inputs += 1;\n this.send(this.hostConnection, encodeHostInputFrame(entry.seat, frame));\n }\n\n /**\n * A frame the room does not act on still spends its lane's flood\n * allowance; one that does not parse is also a strike, and one nested too\n * deep breaks the limits outright.\n */\n private ignore(\n connection: ConnectionId,\n entry: Connection,\n status: \"unknown\" | \"invalid\" | \"too-deep\",\n lane: FrameLane,\n now: number,\n ): void {\n if (status === \"too-deep\" || !entry.budget.spend(lane, now))\n return this.breakLimits(connection, entry, now);\n if (status === \"invalid\") this.strike(connection, entry, now);\n }\n\n private strike(\n connection: ConnectionId,\n entry: Connection,\n now: number,\n ): void {\n this.counters.strikes += 1;\n if (entry.budget.strike(now)) this.breakLimits(connection, entry, now);\n }\n\n /** Sizes are a property of the content, so a breach is final rather than counted. */\n private breakLimits(\n connection: ConnectionId,\n entry: Connection,\n now: number,\n ): void {\n this.connections.delete(connection);\n this.closeConnection(connection, \"limits-broken\");\n this.release(entry, now);\n }\n\n /** What follows a connection ending while its host or seat stays. */\n private release(entry: Connection, now: number): void {\n if (entry.role === \"host\") return this.hostLeft(now);\n const seat = this.seats.get(entry.seat);\n if (seat) this.seatLeft(seat, now);\n }\n\n private hostLeft(now: number): void {\n this.hostConnection = null;\n this.hostAwayUntil = now + this.limits.hostGraceMs;\n this.roomChanged = true;\n this.toPhones({ type: \"host\", present: false });\n }\n\n private seatLeft(seat: Seat, now: number): void {\n seat.connection = null;\n const hold = seat.kind === \"agent\" ? 0 : this.limits.seatHoldMs;\n if (hold === 0) return this.freeSeat(seat, \"dropped\", now);\n seat.holdUntil = now + hold;\n this.changedSeats.add(seat.id);\n this.announceSeat(seat, null);\n this.fact(now, { kind: \"seat-dropped\", seat: seat.id });\n }\n\n private freeSeat(seat: Seat, cause: SeatLeaveCause, at: number): void {\n this.seats.delete(seat.id);\n this.seatsByKey.delete(seat.key);\n this.changedSeats.add(seat.id);\n const left = { type: \"left\", seat: seat.id } as const;\n this.toHost(left);\n this.toPhones(left);\n this.fact(at, { kind: \"seat-left\", seat: seat.id, cause });\n }\n\n private closeRoom(cause: RoomCloseCause, at: number): void {\n const reason = cause === \"restarting\" ? \"restarting\" : \"closed\";\n for (const connection of this.connections.keys())\n this.closeConnection(connection, reason);\n this.connections.clear();\n this.hostConnection = null;\n this.closed = true;\n this.fact(at, { kind: \"closed\", cause });\n }\n\n private announceSeat(\n seat: Seat,\n except: SeatId | null,\n inputBaseline = false,\n ): void {\n const frame = { type: \"seat\", seat: this.seatView(seat) } as const;\n this.toHost(inputBaseline ? { ...frame, inputBaseline: true } : frame);\n for (const other of this.seats.values())\n if (other.id !== except && other.connection !== null)\n this.send(other.connection, frame);\n }\n\n private seatView(seat: Seat): SeatView {\n return {\n id: seat.id,\n label: seat.localSeatLabel ?? seat.label,\n color: seat.color,\n avatarId: seat.avatarId,\n kind: seat.kind,\n connected: seat.connection !== null,\n };\n }\n\n private seatViews(): SeatView[] {\n return [...this.seats.values()].map((seat) => this.seatView(seat));\n }\n\n private toHost(frame: RoomToHostFrame): void {\n if (this.hostConnection !== null) this.send(this.hostConnection, frame);\n }\n\n private toPhones(frame: RoomToPhoneFrame): void {\n const data = encodeFrame(frame);\n for (const seat of this.seats.values())\n if (seat.connection !== null) this.send(seat.connection, data);\n }\n\n private send(\n connection: ConnectionId,\n frame: RoomToHostFrame | RoomToPhoneFrame | string | Uint8Array,\n ): void {\n const data =\n typeof frame === \"string\" || frame instanceof Uint8Array\n ? frame\n : encodeFrame(frame);\n this.effects.push({ send: connection, data });\n }\n\n private closeConnection(\n connection: ConnectionId,\n reason: RoomCloseReason,\n ): void {\n this.effects.push({ close: connection, reason });\n }\n\n private fact(at: number, event: RoomEvent): void {\n this.effects.push({\n fact: {\n at,\n code: this.code,\n instance: this.instance,\n labels: this.labels,\n ...event,\n },\n });\n }\n\n private record(): SavedRoomRecord {\n return {\n code: this.code,\n instance: this.instance,\n hostKey: this.hostKey,\n limits: this.limits,\n labels: this.labels,\n activity: this.activity,\n activityChangeable: this.activityChangeable,\n openedAt: this.openedAt,\n seatsWanted: this.seatsWanted,\n locked: this.locked,\n nextSeatNumber: this.nextSeatNumber,\n hostConnection: this.hostConnection,\n hostAwayUntil: this.hostAwayUntil,\n };\n }\n\n private savedSeat(seat: Seat): SavedSeat {\n return { ...seat };\n }\n}\n","import {\n applyWeighedStatePatch,\n isPlainObject,\n stateWeight,\n type ChannelCopy,\n type HostStateFrame,\n type RoomLimits,\n type RoomStateFrame,\n type SeatId,\n type StateDocument,\n} from \"@air-jam/sdk/room-protocol\";\n\ninterface Copy {\n revision: number;\n document: StateDocument;\n fingerprint?: string;\n private?: string;\n weight: number;\n}\n\nexport interface SavedChannel {\n readonly channel: string;\n readonly revision: number;\n readonly document: StateDocument;\n readonly fingerprint?: string;\n readonly private?: string;\n}\n\nexport type StateOutcome =\n /** The copy took the frame; relay what each phone may see. */\n | {\n readonly kind: \"applied\";\n readonly channel: string;\n readonly frameFor: (seat: SeatId) => RoomStateFrame;\n }\n /** The copy cannot take the patch; ask the host for the document. */\n | { readonly kind: \"need\"; readonly channel: string }\n /** The copy has already asked for the document, and asks again when it is due. */\n | { readonly kind: \"waiting\" }\n | { readonly kind: \"too-large\" }\n | { readonly kind: \"too-many\" };\n\nconst projectEntries = (entries: unknown, seat: SeatId): StateDocument =>\n isPlainObject(entries) && Object.hasOwn(entries, seat)\n ? { [seat]: entries[seat] }\n : {};\n\nconst projectDocument = (copy: Copy, seat: SeatId): StateDocument =>\n copy.private !== undefined && Object.hasOwn(copy.document, copy.private)\n ? {\n ...copy.document,\n [copy.private]: projectEntries(copy.document[copy.private], seat),\n }\n : copy.document;\n\n/** How long the room waits for a document it asked for before asking again; a rate window, so the host's state lane has reopened. */\nexport const REPAIR_RETRY_MS = 1_000;\n\n/**\n * The room's copy of each channel's document. The host is the only writer;\n * the room applies its patches so it can serve a joining or returning device\n * without involving the host, and keeps each seat's private entry from every\n * other seat.\n *\n * A copy falls behind when a patch does not apply or a state frame for it was\n * dropped over the rate. It then asks the host for the whole document, and\n * keeps asking once per `REPAIR_RETRY_MS` until a document lands, since the\n * answer can itself be dropped and a host may send nothing more on its own.\n */\nexport class ChannelCopies {\n private readonly copies = new Map<string, Copy>();\n /** Channels behind the host, and when each next asks for the document. */\n private readonly behind = new Map<string, number>();\n\n constructor(private readonly limits: RoomLimits) {}\n\n receive(frame: HostStateFrame, now: number): StateOutcome {\n return \"document\" in frame\n ? this.receiveDocument(frame)\n : this.receivePatch(frame, now);\n }\n\n /** A state frame for `channel` was dropped; the copy asks for the document at `askAt`. */\n fellBehind(channel: string, askAt: number): void {\n if (this.behind.has(channel) || !this.holds(channel)) return;\n this.behind.set(channel, askAt);\n }\n\n /** The channels whose ask is due at `now`; each next asks a retry later. */\n due(now: number): string[] {\n const due: string[] = [];\n for (const [channel, askAt] of this.behind)\n if (askAt <= now) {\n due.push(channel);\n this.behind.set(channel, now + REPAIR_RETRY_MS);\n }\n return due;\n }\n\n /** When the next ask is due, or null when no copy is behind. */\n nextAsk(): number | null {\n let earliest: number | null = null;\n for (const askAt of this.behind.values())\n if (earliest === null || askAt < earliest) earliest = askAt;\n return earliest;\n }\n\n drop(channel: string): boolean {\n this.behind.delete(channel);\n return this.copies.delete(channel);\n }\n\n forHost(): ChannelCopy[] {\n return [...this.copies].map(([channel, copy]) => ({\n channel,\n revision: copy.revision,\n document: copy.document,\n fingerprint: copy.fingerprint,\n private: copy.private,\n }));\n }\n\n forSeat(seat: SeatId): ChannelCopy[] {\n return [...this.copies].map(([channel, copy]) => ({\n channel,\n revision: copy.revision,\n document: projectDocument(copy, seat),\n }));\n }\n\n saved(channel: string): SavedChannel | null {\n const copy = this.copies.get(channel);\n return copy\n ? {\n channel,\n revision: copy.revision,\n document: copy.document,\n fingerprint: copy.fingerprint,\n private: copy.private,\n }\n : null;\n }\n\n restore(channel: SavedChannel): void {\n this.copies.set(channel.channel, {\n revision: channel.revision,\n document: channel.document,\n fingerprint: channel.fingerprint,\n private: channel.private,\n weight: stateWeight(channel.document),\n });\n }\n\n describe(): Array<{ channel: string; revision: number; weight: number }> {\n return [...this.copies].map(([channel, copy]) => ({\n channel,\n revision: copy.revision,\n weight: copy.weight,\n }));\n }\n\n private receiveDocument(\n frame: Extract<HostStateFrame, { document: StateDocument }>,\n ): StateOutcome {\n if (!this.holds(frame.channel)) return { kind: \"too-many\" };\n const weight = stateWeight(frame.document);\n if (weight > this.limits.stateBytes) return { kind: \"too-large\" };\n const copy: Copy = {\n revision: frame.revision,\n document: frame.document,\n fingerprint: frame.fingerprint,\n private: frame.private,\n weight,\n };\n this.copies.set(frame.channel, copy);\n this.behind.delete(frame.channel);\n return {\n kind: \"applied\",\n channel: frame.channel,\n frameFor: (seat) => ({\n type: \"state\",\n channel: frame.channel,\n revision: frame.revision,\n document: projectDocument(copy, seat),\n }),\n };\n }\n\n /** Whether `channel` has a copy, or room for one within the channel limit. */\n private holds(channel: string): boolean {\n if (this.copies.has(channel) || this.behind.has(channel)) return true;\n let named = this.copies.size;\n for (const name of this.behind.keys())\n if (!this.copies.has(name)) named += 1;\n return named < this.limits.channels;\n }\n\n private receivePatch(\n frame: Exclude<HostStateFrame, { document: StateDocument }>,\n now: number,\n ): StateOutcome {\n const copy = this.copies.get(frame.channel);\n const applied =\n copy && copy.revision === frame.base\n ? applyWeighedStatePatch(copy.document, copy.weight, frame)\n : null;\n if (!copy || !applied) {\n if (this.behind.has(frame.channel)) return { kind: \"waiting\" };\n if (!this.holds(frame.channel)) return { kind: \"too-many\" };\n this.behind.set(frame.channel, now + REPAIR_RETRY_MS);\n return { kind: \"need\", channel: frame.channel };\n }\n if (applied.weight > this.limits.stateBytes) return { kind: \"too-large\" };\n copy.document = applied.document;\n copy.weight = applied.weight;\n copy.revision = frame.revision;\n const privateField = copy.private;\n return {\n kind: \"applied\",\n channel: frame.channel,\n frameFor: (seat) => ({\n type: \"state\",\n channel: frame.channel,\n revision: frame.revision,\n base: frame.base,\n set: frame.set.flatMap(([path, value]) =>\n privateField === undefined || path[0] !== privateField\n ? [[path, value] as [string[], unknown]]\n : path.length === 1\n ? [[path, projectEntries(value, seat)] as [string[], unknown]]\n : path[1] === seat\n ? [[path, value] as [string[], unknown]]\n : [],\n ),\n unset: frame.unset.filter(\n (path) =>\n privateField === undefined ||\n path[0] !== privateField ||\n path.length === 1 ||\n path[1] === seat,\n ),\n }),\n };\n }\n}\n","import type { RoomLimits } from \"@air-jam/sdk/room-protocol\";\n\nexport type FrameLane = \"input\" | \"state\" | \"frame\";\n\n/** What the room does with one arriving frame. */\nexport type Admission = \"admitted\" | \"over-rate\" | \"flooded\";\n\nconst WINDOW_MS = 1000;\n/** The flood allowance earns this many times the lane's rate each second. */\nconst FLOOD_EARNING_FACTOR = 2;\n/** Seconds of the lane's rate the allowance starts with. */\nconst FLOOD_START_SECONDS = 10;\n/** Seconds of the lane's rate the allowance holds at most. */\nconst FLOOD_CAPACITY_SECONDS = 30;\n\nconst laneLimit = (limits: RoomLimits, lane: FrameLane): number =>\n lane === \"input\"\n ? limits.inputsPerSecond\n : lane === \"state\"\n ? limits.statesPerSecond\n : limits.framesPerSecond;\n\nconst LANES: readonly FrameLane[] = [\"input\", \"state\", \"frame\"];\n\n/**\n * One connection's rates, against the time the room is given.\n *\n * Each lane admits its rate in fixed one-second windows; a frame past it is\n * over-rate and dropped without blame, because a network stall delivers a\n * phone's buffered frames in one burst. Every arrival, admitted, dropped or\n * ignored, also spends the lane's flood allowance, which earns twice the lane's rate each\n * second the connection lives: a stall's backlog was earned while the\n * connection was silent, so only a connection that keeps sending well over\n * its rate runs the allowance out and floods.\n *\n * Frames that do not parse are strikes, counted per second as before.\n */\nexport class ConnectionBudget {\n private windowStart: number;\n private readonly counts: Record<FrameLane, number> = {\n input: 0,\n state: 0,\n frame: 0,\n };\n private readonly allowance: Record<FrameLane, number>;\n private allowanceAt: number;\n private strikes = 0;\n\n constructor(\n private readonly limits: RoomLimits,\n now: number,\n ) {\n this.windowStart = now;\n this.allowanceAt = now;\n this.allowance = {\n input: laneLimit(limits, \"input\") * FLOOD_START_SECONDS,\n state: laneLimit(limits, \"state\") * FLOOD_START_SECONDS,\n frame: laneLimit(limits, \"frame\") * FLOOD_START_SECONDS,\n };\n }\n\n /** When the current rate window ends and over-rate lanes take frames again. */\n get windowEndsAt(): number {\n return this.windowStart + WINDOW_MS;\n }\n\n admit(lane: FrameLane, now: number): Admission {\n if (!this.spend(lane, now)) return \"flooded\";\n return this.fits(lane, now) ? \"admitted\" : \"over-rate\";\n }\n\n /** Spends one arrival from the lane's flood allowance, as a frame the room ignores does; false once it runs out. */\n spend(lane: FrameLane, now: number): boolean {\n this.earn(now);\n this.allowance[lane] -= 1;\n return this.allowance[lane] >= 0;\n }\n\n /** Takes a frame that arrived earlier into the rate window, without spending allowance again. */\n fits(lane: FrameLane, now: number): boolean {\n this.advance(now);\n this.counts[lane] += 1;\n return this.counts[lane] <= laneLimit(this.limits, lane);\n }\n\n /** Records a frame that did not parse; true when the connection has broken its limits. */\n strike(now: number): boolean {\n this.advance(now);\n this.strikes += 1;\n return this.strikes > this.limits.strikesPerSecond;\n }\n\n private earn(now: number): void {\n const seconds = (now - this.allowanceAt) / 1000;\n this.allowanceAt = now;\n if (seconds <= 0) return;\n for (const lane of LANES) {\n const rate = laneLimit(this.limits, lane);\n this.allowance[lane] = Math.min(\n rate * FLOOD_CAPACITY_SECONDS,\n this.allowance[lane] + rate * FLOOD_EARNING_FACTOR * seconds,\n );\n }\n }\n\n private advance(now: number): void {\n if (now - this.windowStart < WINDOW_MS) return;\n this.windowStart = now;\n this.counts.input = 0;\n this.counts.state = 0;\n this.counts.frame = 0;\n this.strikes = 0;\n }\n}\n","/** Compares two secrets in time that depends only on their lengths. */\nexport const sameSecret = (given: string, expected: string): boolean => {\n let difference = given.length ^ expected.length;\n for (let index = 0; index < expected.length; index += 1)\n difference |=\n (given.charCodeAt(index % Math.max(given.length, 1)) || 0) ^\n expected.charCodeAt(index);\n return difference === 0;\n};\n","import {\n encodeFrame,\n joinHostInputFrames,\n parseHostHello,\n PING_FRAME,\n PONG_FRAME,\n ROOM_CODE_ALPHABET,\n ROOM_CODE_LENGTH,\n roomCloseCodes,\n type HostHello,\n type RoomAcceptor,\n type RoomAddress,\n type RoomCloseReason,\n type RoomConnection,\n type RoomConnectionHandlers,\n type RoomWireData,\n} from \"@air-jam/sdk/room-protocol\";\nimport { systemRoomClock, type RoomClock } from \"@air-jam/sdk/room-session\";\nimport type { RoomFact } from \"../room/facts.js\";\nimport type { RoomGate } from \"../room/gate.js\";\nimport { Room, type RoomDescription, type RoomEffect } from \"../room/room.js\";\nimport type { ConnectionId } from \"../room/saved-room.js\";\n\nexport interface MemoryRoomHostOptions {\n readonly gate: RoomGate;\n /** Whether a host may ask for its room's code, as a local server allows; hosted rooms choose. */\n readonly codesMayBeAsked: boolean;\n readonly clock?: RoomClock;\n /**\n * Runs `flush` once the work of the current turn is done. Input bound for\n * one host that became ready in the same turn leaves as one message; the\n * default packs what one synchronous run produced.\n */\n readonly afterTurn?: (flush: () => void) => void;\n readonly onFact?: (fact: RoomFact) => void;\n /** A gate that failed; the host was told to try later. */\n readonly onGateError?: (error: unknown) => void;\n /** How long a queued host waits before the gate is asked again. */\n readonly gateRetryMs?: number;\n}\n\n/** Frames a device may send before its room exists, while the gate decides. */\nconst ADMISSION_BUFFER_FRAMES = 16;\n/** How long a connection may stay open without saying hello. */\nexport const HELLO_DEADLINE_MS = 15_000;\n\ntype Stage = \"hello\" | \"admitting\" | \"bound\" | \"closed\";\n\ninterface Accepted {\n readonly id: ConnectionId;\n readonly address: RoomAddress;\n readonly origin: string | null;\n readonly transport: RoomConnection;\n stage: Stage;\n room: HostedRoom | null;\n readonly buffered: RoomWireData[];\n cancelGateRetry: (() => void) | null;\n cancelHelloDeadline: (() => void) | null;\n}\n\ninterface HostedRoom {\n readonly code: string;\n readonly room: Room;\n wakeAt: number | null;\n cancelWake: (() => void) | null;\n}\n\nconst randomCode = (): string =>\n Array.from(\n crypto.getRandomValues(new Uint8Array(ROOM_CODE_LENGTH)),\n (byte) => ROOM_CODE_ALPHABET[byte % ROOM_CODE_ALPHABET.length],\n ).join(\"\");\n\n/**\n * Rooms held in memory, for the Node server and for in-process loopback\n * links. It owns only wiring: it routes a connection by its path, runs the\n * gate before a room exists, calls the room with the role from the path,\n * applies the effects the room returns, keeps one timer per room for its\n * next deadline and packs host-bound input that is ready together. Every\n * room rule is the room's own.\n */\nexport class MemoryRoomHost implements RoomAcceptor {\n private readonly rooms = new Map<string, HostedRoom>();\n private readonly connections = new Map<ConnectionId, Accepted>();\n private readonly pendingInput = new Map<ConnectionId, Uint8Array[]>();\n private flushScheduled = false;\n private nextConnection = 1;\n private stopped = false;\n private readonly clock: RoomClock;\n private readonly afterTurn: (flush: () => void) => void;\n\n constructor(private readonly options: MemoryRoomHostOptions) {\n this.clock = options.clock ?? systemRoomClock;\n this.afterTurn = options.afterTurn ?? queueMicrotask;\n }\n\n accept(\n address: RoomAddress,\n origin: string | null,\n transport: RoomConnection,\n ): RoomConnectionHandlers {\n const accepted: Accepted = {\n id: `c${this.nextConnection}`,\n address,\n origin,\n transport,\n stage: \"hello\",\n room: null,\n buffered: [],\n cancelGateRetry: null,\n cancelHelloDeadline: null,\n };\n this.nextConnection += 1;\n this.connections.set(accepted.id, accepted);\n if (this.stopped) this.closeConnection(accepted, \"restarting\");\n else\n accepted.cancelHelloDeadline = this.clock.at(\n this.clock.now() + HELLO_DEADLINE_MS,\n () => {\n accepted.cancelHelloDeadline = null;\n if (accepted.stage === \"hello\")\n this.closeConnection(accepted, \"try-later\");\n },\n );\n return {\n receive: (data) => this.receive(accepted, data),\n closed: () => this.closed(accepted),\n };\n }\n\n /** Stops every room as the server goes down; its devices are told to come back. */\n stop(): void {\n this.stopped = true;\n for (const hosted of [...this.rooms.values()])\n this.call(hosted, (room, now) => room.stop(\"restarting\", now));\n for (const accepted of [...this.connections.values()])\n if (accepted.stage !== \"bound\")\n this.closeConnection(accepted, \"restarting\");\n }\n\n describe(): RoomDescription[] {\n return [...this.rooms.values()].map((hosted) => hosted.room.describe());\n }\n\n private receive(accepted: Accepted, data: RoomWireData): void {\n if (data === PING_FRAME) return accepted.transport.send(PONG_FRAME);\n switch (accepted.stage) {\n case \"closed\":\n return;\n case \"bound\": {\n const hosted = accepted.room;\n if (!hosted) throw new Error(`Connection ${accepted.id} has no room.`);\n return this.call(hosted, (room, now) =>\n room.receive(accepted.id, data, now),\n );\n }\n case \"admitting\":\n if (accepted.buffered.length >= ADMISSION_BUFFER_FRAMES)\n return this.closeConnection(accepted, \"limits-broken\");\n accepted.buffered.push(data);\n return;\n case \"hello\":\n if (typeof data !== \"string\")\n return this.closeConnection(accepted, \"unsupported-version\");\n return this.hello(accepted, data);\n }\n }\n\n private hello(accepted: Accepted, hello: string): void {\n accepted.cancelHelloDeadline?.();\n accepted.cancelHelloDeadline = null;\n const { address } = accepted;\n const existing =\n address.code === null ? undefined : this.rooms.get(address.code);\n if (existing) return this.bind(accepted, existing, hello);\n if (address.role === \"phone\")\n return this.closeConnection(accepted, \"not-found\");\n const frame = parseHostHello(hello);\n if (!frame) return this.closeConnection(accepted, \"unsupported-version\");\n // A resume names an instance that is gone; only a fresh hello opens a room.\n if (\n frame.instance !== undefined ||\n (address.code !== null && !this.options.codesMayBeAsked)\n )\n return this.closeConnection(accepted, \"not-found\");\n accepted.stage = \"admitting\";\n void this.admit(accepted, frame, hello);\n }\n\n private async admit(\n accepted: Accepted,\n frame: HostHello,\n hello: string,\n ): Promise<void> {\n let decision;\n try {\n decision = await this.options.gate.admit({\n hello: frame,\n origin: accepted.origin,\n });\n } catch (error) {\n this.options.onGateError?.(error);\n return this.closeConnection(accepted, \"try-later\");\n }\n if (accepted.stage !== \"admitting\") return;\n if (this.stopped) return this.closeConnection(accepted, \"restarting\");\n if (decision.outcome === \"refuse\")\n return this.closeConnection(accepted, decision.reason);\n if (decision.outcome === \"wait\") {\n accepted.transport.send(\n encodeFrame({ type: \"wait\", position: decision.position }),\n );\n accepted.cancelGateRetry = this.clock.at(\n this.clock.now() + (this.options.gateRetryMs ?? 2_000),\n () => {\n accepted.cancelGateRetry = null;\n void this.admit(accepted, frame, hello);\n },\n );\n return;\n }\n const code = accepted.address.code ?? this.freeCode();\n // A host that asked for a code may find another host opened it meanwhile.\n const existing = this.rooms.get(code);\n if (existing) return this.bind(accepted, existing, hello);\n const opened = Room.open(\n {\n code,\n instance: crypto.randomUUID(),\n hostKey: frame.key,\n limits: decision.limits,\n labels: decision.labels,\n activity: decision.activity,\n activityChangeable: decision.activityChangeable,\n },\n this.clock.now(),\n );\n const hosted: HostedRoom = {\n code,\n room: opened.room,\n wakeAt: null,\n cancelWake: null,\n };\n this.rooms.set(code, hosted);\n this.apply(hosted, opened.effects);\n this.bind(accepted, hosted, hello);\n }\n\n private bind(accepted: Accepted, hosted: HostedRoom, hello: string): void {\n accepted.stage = \"bound\";\n accepted.room = hosted;\n this.call(hosted, (room, now) =>\n room.connect(accepted.id, accepted.address.role, hello, now),\n );\n for (const data of accepted.buffered.splice(0))\n this.receive(accepted, data);\n }\n\n private closed(accepted: Accepted): void {\n const stage = accepted.stage;\n if (stage === \"closed\") return;\n this.forget(accepted);\n const hosted = accepted.room;\n if (stage === \"bound\" && hosted)\n this.call(hosted, (room, now) => room.disconnect(accepted.id, now));\n }\n\n private call(\n hosted: HostedRoom,\n work: (room: Room, now: number) => RoomEffect[],\n ): void {\n this.apply(hosted, work(hosted.room, this.clock.now()));\n this.scheduleWake(hosted);\n }\n\n private apply(hosted: HostedRoom, effects: readonly RoomEffect[]): void {\n for (const effect of effects) {\n if (\"fact\" in effect) {\n this.options.onFact?.(effect.fact);\n if (effect.fact.kind === \"closed\") this.retire(hosted);\n continue;\n }\n const target =\n \"send\" in effect\n ? this.connections.get(effect.send)\n : this.connections.get(effect.close);\n if (!target) continue;\n if (\"close\" in effect) this.closeConnection(target, effect.reason);\n else if (effect.data instanceof Uint8Array)\n this.queueInput(target, effect.data);\n else {\n this.flushInput(target);\n target.transport.send(effect.data);\n }\n }\n }\n\n private scheduleWake(hosted: HostedRoom): void {\n const next =\n this.rooms.get(hosted.code) === hosted ? hosted.room.nextWake() : null;\n if (next === hosted.wakeAt) return;\n hosted.cancelWake?.();\n hosted.cancelWake = null;\n hosted.wakeAt = next;\n if (next === null) return;\n hosted.cancelWake = this.clock.at(next, () => {\n hosted.cancelWake = null;\n hosted.wakeAt = null;\n this.call(hosted, (room, now) => room.wake(now));\n });\n }\n\n private retire(hosted: HostedRoom): void {\n if (this.rooms.get(hosted.code) === hosted) this.rooms.delete(hosted.code);\n hosted.cancelWake?.();\n hosted.cancelWake = null;\n }\n\n private queueInput(target: Accepted, frame: Uint8Array): void {\n const queued = this.pendingInput.get(target.id);\n if (queued) queued.push(frame);\n else this.pendingInput.set(target.id, [frame]);\n if (this.flushScheduled) return;\n this.flushScheduled = true;\n this.afterTurn(() => {\n this.flushScheduled = false;\n for (const id of [...this.pendingInput.keys()]) {\n const connection = this.connections.get(id);\n if (connection) this.flushInput(connection);\n }\n });\n }\n\n /** Sends what is queued for a host before anything that follows it, keeping order. */\n private flushInput(target: Accepted): void {\n const frames = this.pendingInput.get(target.id);\n if (!frames) return;\n this.pendingInput.delete(target.id);\n target.transport.send(\n frames.length === 1 && frames[0]\n ? frames[0]\n : joinHostInputFrames(frames),\n );\n }\n\n private closeConnection(accepted: Accepted, reason: RoomCloseReason): void {\n if (accepted.stage === \"closed\") return;\n this.forget(accepted);\n accepted.transport.close(roomCloseCodes[reason].code);\n }\n\n private forget(accepted: Accepted): void {\n accepted.stage = \"closed\";\n accepted.cancelGateRetry?.();\n accepted.cancelGateRetry = null;\n accepted.cancelHelloDeadline?.();\n accepted.cancelHelloDeadline = null;\n this.connections.delete(accepted.id);\n this.pendingInput.delete(accepted.id);\n }\n\n private freeCode(): string {\n for (;;) {\n const code = randomCode();\n if (!this.rooms.has(code)) return code;\n }\n }\n}\n","import {\n DEFAULT_ROOM_LIMITS,\n type HostHello,\n type RoomLimits,\n} from \"@air-jam/sdk/room-protocol\";\nimport type { RoomLabels } from \"./facts.js\";\nimport { sameSecret } from \"./secrets.js\";\n\nexport interface RoomGateRequest {\n readonly hello: HostHello;\n /** The connection's origin header, when the transport has one. */\n readonly origin: string | null;\n}\n\n/**\n * The gate answers whether a host may open a room, before the room exists.\n * It runs in the host's front door, not in the room, so it may take its time.\n */\nexport type RoomGateDecision =\n | {\n readonly outcome: \"open\";\n readonly limits: RoomLimits;\n readonly labels: RoomLabels;\n readonly activity: string | null;\n readonly activityChangeable: boolean;\n }\n /** Admission is queued; the front door tells the host its place. */\n | { readonly outcome: \"wait\"; readonly position: number }\n | {\n readonly outcome: \"refuse\";\n readonly reason: \"unauthorised\" | \"try-later\";\n };\n\nexport interface RoomGate {\n admit(request: RoomGateRequest): RoomGateDecision | Promise<RoomGateDecision>;\n}\n\nconst openDecision = (\n limits: RoomLimits,\n activityChangeable: boolean,\n): RoomGateDecision => ({\n outcome: \"open\",\n limits,\n labels: {},\n activity: null,\n activityChangeable,\n});\n\n/** Admits every host, as a local or private server does. */\nexport const createOpenRoomGate = (\n limits: RoomLimits = DEFAULT_ROOM_LIMITS,\n): RoomGate => ({\n admit: () => openDecision(limits, true),\n});\n\n/**\n * Admits hosts whose credential is the server's shared master key. Such a\n * host runs one game, so it may not change what is on screen.\n */\nexport const createMasterKeyRoomGate = (\n masterKey: string,\n limits: RoomLimits = DEFAULT_ROOM_LIMITS,\n): RoomGate => {\n if (masterKey.length === 0)\n throw new Error(\"A master key gate needs a master key.\");\n return {\n admit: ({ hello }) =>\n hello.credential !== undefined && sameSecret(hello.credential, masterKey)\n ? openDecision(limits, false)\n : { outcome: \"refuse\", reason: \"unauthorised\" },\n };\n};\n"],"mappings":";AASO,IAAM,mBAAmB;;;ACThC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAaK;;;AC1BP;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d,MAAM,eAAe,UAAa,WAAW,MAAM,YAAY,SAAS,IACpE,aAAa,QAAQ,KAAK,IAC1B,EAAE,SAAS,UAAU,QAAQ,eAAe;AAAA,EACpD;AACF;","names":["seat","encodeFrame","parseHostHello","PING_FRAME","PONG_FRAME","PING_FRAME","PONG_FRAME","parseHostHello","encodeFrame"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// src/env/load-workspace-env.ts
|
|
2
|
+
import dotenv from "dotenv";
|
|
3
|
+
import { existsSync } from "fs";
|
|
4
|
+
import { dirname, resolve } from "path";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
var MODULE_DIR = dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
var SERVER_PACKAGE_ROOT = resolve(MODULE_DIR, "..", "..");
|
|
8
|
+
var WORKSPACE_ROOT = resolve(SERVER_PACKAGE_ROOT, "..", "..");
|
|
9
|
+
var DEFAULT_ENV_CANDIDATES = {
|
|
10
|
+
rootEnvLocal: resolve(WORKSPACE_ROOT, ".env.local"),
|
|
11
|
+
serverEnv: resolve(SERVER_PACKAGE_ROOT, ".env")
|
|
12
|
+
};
|
|
13
|
+
var loadedEnvCandidates = /* @__PURE__ */ new Set();
|
|
14
|
+
var resolveWorkspaceEnvCandidatePaths = ({
|
|
15
|
+
cwd,
|
|
16
|
+
candidates = DEFAULT_ENV_CANDIDATES
|
|
17
|
+
} = {}) => {
|
|
18
|
+
const resolvedPaths = [];
|
|
19
|
+
if (cwd) {
|
|
20
|
+
resolvedPaths.push(resolve(cwd, ".env.local"));
|
|
21
|
+
}
|
|
22
|
+
resolvedPaths.push(candidates.rootEnvLocal, candidates.serverEnv);
|
|
23
|
+
return [...new Set(resolvedPaths)];
|
|
24
|
+
};
|
|
25
|
+
var loadWorkspaceEnv = ({
|
|
26
|
+
processEnv = process.env,
|
|
27
|
+
candidates = DEFAULT_ENV_CANDIDATES,
|
|
28
|
+
cwd = process.cwd()
|
|
29
|
+
} = {}) => {
|
|
30
|
+
for (const candidate of resolveWorkspaceEnvCandidatePaths({
|
|
31
|
+
cwd,
|
|
32
|
+
candidates
|
|
33
|
+
})) {
|
|
34
|
+
if (loadedEnvCandidates.has(candidate)) {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (!existsSync(candidate)) {
|
|
38
|
+
loadedEnvCandidates.add(candidate);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
dotenv.config({
|
|
42
|
+
path: candidate,
|
|
43
|
+
override: false,
|
|
44
|
+
quiet: true,
|
|
45
|
+
processEnv
|
|
46
|
+
});
|
|
47
|
+
loadedEnvCandidates.add(candidate);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export {
|
|
52
|
+
loadWorkspaceEnv
|
|
53
|
+
};
|
|
54
|
+
//# sourceMappingURL=chunk-GMZVQDC6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/env/load-workspace-env.ts"],"sourcesContent":["import dotenv from \"dotenv\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst MODULE_DIR = dirname(fileURLToPath(import.meta.url));\nconst SERVER_PACKAGE_ROOT = resolve(MODULE_DIR, \"..\", \"..\");\nconst WORKSPACE_ROOT = resolve(SERVER_PACKAGE_ROOT, \"..\", \"..\");\n\nexport interface WorkspaceEnvCandidates {\n rootEnvLocal: string;\n serverEnv: string;\n}\n\nexport interface LoadWorkspaceEnvOptions {\n processEnv?: Record<string, string | undefined>;\n candidates?: WorkspaceEnvCandidates;\n cwd?: string;\n}\n\nconst DEFAULT_ENV_CANDIDATES: WorkspaceEnvCandidates = {\n rootEnvLocal: resolve(WORKSPACE_ROOT, \".env.local\"),\n serverEnv: resolve(SERVER_PACKAGE_ROOT, \".env\"),\n};\n\nconst loadedEnvCandidates = new Set<string>();\n\nexport const resolveWorkspaceEnvCandidatePaths = ({\n cwd,\n candidates = DEFAULT_ENV_CANDIDATES,\n}: Pick<LoadWorkspaceEnvOptions, \"candidates\" | \"cwd\"> = {}) => {\n const resolvedPaths = [];\n\n if (cwd) {\n resolvedPaths.push(resolve(cwd, \".env.local\"));\n }\n\n resolvedPaths.push(candidates.rootEnvLocal, candidates.serverEnv);\n\n return [...new Set(resolvedPaths)];\n};\n\nexport const loadWorkspaceEnv = ({\n processEnv = process.env,\n candidates = DEFAULT_ENV_CANDIDATES,\n cwd = process.cwd(),\n}: LoadWorkspaceEnvOptions = {}): void => {\n for (const candidate of resolveWorkspaceEnvCandidatePaths({\n cwd,\n candidates,\n })) {\n if (loadedEnvCandidates.has(candidate)) {\n continue;\n }\n\n if (!existsSync(candidate)) {\n loadedEnvCandidates.add(candidate);\n continue;\n }\n\n dotenv.config({\n path: candidate,\n override: false,\n quiet: true,\n processEnv: processEnv as Record<string, string>,\n });\n loadedEnvCandidates.add(candidate);\n }\n};\n\nexport const resetWorkspaceEnvLoaderForTests = (): void => {\n loadedEnvCandidates.clear();\n};\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;AAE9B,IAAM,aAAa,QAAQ,cAAc,YAAY,GAAG,CAAC;AACzD,IAAM,sBAAsB,QAAQ,YAAY,MAAM,IAAI;AAC1D,IAAM,iBAAiB,QAAQ,qBAAqB,MAAM,IAAI;AAa9D,IAAM,yBAAiD;AAAA,EACrD,cAAc,QAAQ,gBAAgB,YAAY;AAAA,EAClD,WAAW,QAAQ,qBAAqB,MAAM;AAChD;AAEA,IAAM,sBAAsB,oBAAI,IAAY;AAErC,IAAM,oCAAoC,CAAC;AAAA,EAChD;AAAA,EACA,aAAa;AACf,IAAyD,CAAC,MAAM;AAC9D,QAAM,gBAAgB,CAAC;AAEvB,MAAI,KAAK;AACP,kBAAc,KAAK,QAAQ,KAAK,YAAY,CAAC;AAAA,EAC/C;AAEA,gBAAc,KAAK,WAAW,cAAc,WAAW,SAAS;AAEhE,SAAO,CAAC,GAAG,IAAI,IAAI,aAAa,CAAC;AACnC;AAEO,IAAM,mBAAmB,CAAC;AAAA,EAC/B,aAAa,QAAQ;AAAA,EACrB,aAAa;AAAA,EACb,MAAM,QAAQ,IAAI;AACpB,IAA6B,CAAC,MAAY;AACxC,aAAW,aAAa,kCAAkC;AAAA,IACxD;AAAA,IACA;AAAA,EACF,CAAC,GAAG;AACF,QAAI,oBAAoB,IAAI,SAAS,GAAG;AACtC;AAAA,IACF;AAEA,QAAI,CAAC,WAAW,SAAS,GAAG;AAC1B,0BAAoB,IAAI,SAAS;AACjC;AAAA,IACF;AAEA,WAAO,OAAO;AAAA,MACZ,MAAM;AAAA,MACN,UAAU;AAAA,MACV,OAAO;AAAA,MACP;AAAA,IACF,CAAC;AACD,wBAAoB,IAAI,SAAS;AAAA,EACnC;AACF;","names":[]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createServerLogger
|
|
3
|
+
} from "./chunk-2BHF5ZCS.js";
|
|
4
|
+
|
|
5
|
+
// src/process-lifecycle.ts
|
|
6
|
+
var installServerProcessSignalHandlers = ({
|
|
7
|
+
runtime,
|
|
8
|
+
logger = createServerLogger({
|
|
9
|
+
service: "air-jam-server",
|
|
10
|
+
component: "process-lifecycle"
|
|
11
|
+
})
|
|
12
|
+
}) => {
|
|
13
|
+
let stopping = false;
|
|
14
|
+
const removeHandlers = () => {
|
|
15
|
+
process.off("SIGINT", handleSignal);
|
|
16
|
+
process.off("SIGTERM", handleSignal);
|
|
17
|
+
};
|
|
18
|
+
const handleSignal = (signal) => {
|
|
19
|
+
if (stopping) return;
|
|
20
|
+
stopping = true;
|
|
21
|
+
removeHandlers();
|
|
22
|
+
logger.info({ signal }, "Room server stopping");
|
|
23
|
+
runtime.stop().then(
|
|
24
|
+
() => logger.info({ signal }, "Room server stopped"),
|
|
25
|
+
(error) => {
|
|
26
|
+
process.exitCode = 1;
|
|
27
|
+
logger.error({ err: error, signal }, "Room server stop failed");
|
|
28
|
+
}
|
|
29
|
+
);
|
|
30
|
+
};
|
|
31
|
+
process.once("SIGINT", handleSignal);
|
|
32
|
+
process.once("SIGTERM", handleSignal);
|
|
33
|
+
return removeHandlers;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export {
|
|
37
|
+
installServerProcessSignalHandlers
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=chunk-ILYZVHYT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/process-lifecycle.ts"],"sourcesContent":["import { createServerLogger, type ServerLogger } from \"./logging/logger.js\";\nimport type { RoomServerRuntime } from \"./room-server/room-server.js\";\n\ntype ShutdownSignal = \"SIGINT\" | \"SIGTERM\";\n\n/**\n * Stops the room server once on SIGINT or SIGTERM: every room closes its\n * devices as \"restarting\", so they come back to the next server. Returns\n * the call that removes the handlers.\n */\nexport const installServerProcessSignalHandlers = ({\n runtime,\n logger = createServerLogger({\n service: \"air-jam-server\",\n component: \"process-lifecycle\",\n }),\n}: {\n runtime: Pick<RoomServerRuntime, \"stop\">;\n logger?: ServerLogger;\n}): (() => void) => {\n let stopping = false;\n\n const removeHandlers = (): void => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n\n const handleSignal = (signal: ShutdownSignal): void => {\n if (stopping) return;\n stopping = true;\n removeHandlers();\n logger.info({ signal }, \"Room server stopping\");\n runtime.stop().then(\n () => logger.info({ signal }, \"Room server stopped\"),\n (error: unknown) => {\n process.exitCode = 1;\n logger.error({ err: error, signal }, \"Room server stop failed\");\n },\n );\n };\n\n process.once(\"SIGINT\", handleSignal);\n process.once(\"SIGTERM\", handleSignal);\n return removeHandlers;\n};\n"],"mappings":";;;;;AAUO,IAAM,qCAAqC,CAAC;AAAA,EACjD;AAAA,EACA,SAAS,mBAAmB;AAAA,IAC1B,SAAS;AAAA,IACT,WAAW;AAAA,EACb,CAAC;AACH,MAGoB;AAClB,MAAI,WAAW;AAEf,QAAM,iBAAiB,MAAY;AACjC,YAAQ,IAAI,UAAU,YAAY;AAClC,YAAQ,IAAI,WAAW,YAAY;AAAA,EACrC;AAEA,QAAM,eAAe,CAAC,WAAiC;AACrD,QAAI,SAAU;AACd,eAAW;AACX,mBAAe;AACf,WAAO,KAAK,EAAE,OAAO,GAAG,sBAAsB;AAC9C,YAAQ,KAAK,EAAE;AAAA,MACb,MAAM,OAAO,KAAK,EAAE,OAAO,GAAG,qBAAqB;AAAA,MACnD,CAAC,UAAmB;AAClB,gBAAQ,WAAW;AACnB,eAAO,MAAM,EAAE,KAAK,OAAO,OAAO,GAAG,yBAAyB;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AAEA,UAAQ,KAAK,UAAU,YAAY;AACnC,UAAQ,KAAK,WAAW,YAAY;AACpC,SAAO;AACT;","names":[]}
|