@air-jam/devtools 0.0.0-stage → 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.
Files changed (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/dist/chunk-2O67AXCU.js +470 -0
  4. package/dist/chunk-2O67AXCU.js.map +1 -0
  5. package/dist/chunk-AO3ZDXF6.js +142 -0
  6. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  7. package/dist/chunk-ART5TEYT.js +472 -0
  8. package/dist/chunk-ART5TEYT.js.map +1 -0
  9. package/dist/chunk-ASC2CK2R.js +77 -0
  10. package/dist/chunk-ASC2CK2R.js.map +1 -0
  11. package/dist/chunk-E3UZZGAV.js +50 -0
  12. package/dist/chunk-E3UZZGAV.js.map +1 -0
  13. package/dist/chunk-EJTE7UKX.js +64 -0
  14. package/dist/chunk-EJTE7UKX.js.map +1 -0
  15. package/dist/chunk-ESFKNN75.js +110 -0
  16. package/dist/chunk-ESFKNN75.js.map +1 -0
  17. package/dist/chunk-EU7A6PXW.js +1339 -0
  18. package/dist/chunk-EU7A6PXW.js.map +1 -0
  19. package/dist/chunk-FN7E6EA7.js +549 -0
  20. package/dist/chunk-FN7E6EA7.js.map +1 -0
  21. package/dist/chunk-GDFAWHGA.js +190 -0
  22. package/dist/chunk-GDFAWHGA.js.map +1 -0
  23. package/dist/chunk-HZUGBH4Y.js +347 -0
  24. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  25. package/dist/chunk-ITKAOEGX.js +93 -0
  26. package/dist/chunk-ITKAOEGX.js.map +1 -0
  27. package/dist/chunk-JBCUTWRI.js +897 -0
  28. package/dist/chunk-JBCUTWRI.js.map +1 -0
  29. package/dist/chunk-JSI5S4WP.js +1174 -0
  30. package/dist/chunk-JSI5S4WP.js.map +1 -0
  31. package/dist/chunk-L4D675BG.js +97 -0
  32. package/dist/chunk-L4D675BG.js.map +1 -0
  33. package/dist/chunk-M6CJ7GQC.js +133 -0
  34. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  35. package/dist/chunk-MEIMOSZC.js +749 -0
  36. package/dist/chunk-MEIMOSZC.js.map +1 -0
  37. package/dist/chunk-O3XG3FNL.js +1014 -0
  38. package/dist/chunk-O3XG3FNL.js.map +1 -0
  39. package/dist/chunk-OM6SCJ7H.js +18 -0
  40. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  41. package/dist/chunk-PKD4WVX5.js +63 -0
  42. package/dist/chunk-PKD4WVX5.js.map +1 -0
  43. package/dist/chunk-PMBLXGFM.js +3384 -0
  44. package/dist/chunk-PMBLXGFM.js.map +1 -0
  45. package/dist/chunk-PMNE5GIN.js +279 -0
  46. package/dist/chunk-PMNE5GIN.js.map +1 -0
  47. package/dist/chunk-QAWI64VR.js +148 -0
  48. package/dist/chunk-QAWI64VR.js.map +1 -0
  49. package/dist/chunk-QGADSPHZ.js +449 -0
  50. package/dist/chunk-QGADSPHZ.js.map +1 -0
  51. package/dist/chunk-SPYN66UV.js +338 -0
  52. package/dist/chunk-SPYN66UV.js.map +1 -0
  53. package/dist/context.d.ts +19 -0
  54. package/dist/context.js +10 -0
  55. package/dist/context.js.map +1 -0
  56. package/dist/controller.d.ts +67 -0
  57. package/dist/controller.js +40 -0
  58. package/dist/controller.js.map +1 -0
  59. package/dist/dependencies.d.ts +44 -0
  60. package/dist/dependencies.js +10 -0
  61. package/dist/dependencies.js.map +1 -0
  62. package/dist/dev.d.ts +21 -0
  63. package/dist/dev.js +19 -0
  64. package/dist/dev.js.map +1 -0
  65. package/dist/game-builds.d.ts +200 -0
  66. package/dist/game-builds.js +16 -0
  67. package/dist/game-builds.js.map +1 -0
  68. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  69. package/dist/game-runs.d.ts +1452 -0
  70. package/dist/game-runs.js +76 -0
  71. package/dist/game-runs.js.map +1 -0
  72. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  73. package/dist/game-session-broker.d.ts +4 -0
  74. package/dist/game-session-broker.js +40 -0
  75. package/dist/game-session-broker.js.map +1 -0
  76. package/dist/game-session.d.ts +3934 -0
  77. package/dist/game-session.js +195 -0
  78. package/dist/game-session.js.map +1 -0
  79. package/dist/game-settings.d.ts +16 -0
  80. package/dist/game-settings.js +237 -0
  81. package/dist/game-settings.js.map +1 -0
  82. package/dist/games.d.ts +28 -0
  83. package/dist/games.js +16 -0
  84. package/dist/games.js.map +1 -0
  85. package/dist/harness/visual.d.ts +204 -0
  86. package/dist/harness/visual.js +46 -0
  87. package/dist/harness/visual.js.map +1 -0
  88. package/dist/logs.d.ts +15 -0
  89. package/dist/logs.js +57 -0
  90. package/dist/logs.js.map +1 -0
  91. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  92. package/dist/mcp-config.d.ts +63 -0
  93. package/dist/mcp-config.js +191 -0
  94. package/dist/mcp-config.js.map +1 -0
  95. package/dist/platform-auth.d.ts +9 -0
  96. package/dist/platform-auth.js +45 -0
  97. package/dist/platform-auth.js.map +1 -0
  98. package/dist/platform-game-analytics.d.ts +51 -0
  99. package/dist/platform-game-analytics.js +49 -0
  100. package/dist/platform-game-analytics.js.map +1 -0
  101. package/dist/platform-game-app-id.d.ts +46 -0
  102. package/dist/platform-game-app-id.js +93 -0
  103. package/dist/platform-game-app-id.js.map +1 -0
  104. package/dist/platform-game-media.d.ts +347 -0
  105. package/dist/platform-game-media.js +168 -0
  106. package/dist/platform-game-media.js.map +1 -0
  107. package/dist/platform-games.d.ts +87 -0
  108. package/dist/platform-games.js +183 -0
  109. package/dist/platform-games.js.map +1 -0
  110. package/dist/quality.d.ts +16 -0
  111. package/dist/quality.js +62 -0
  112. package/dist/quality.js.map +1 -0
  113. package/dist/release.d.ts +1304 -0
  114. package/dist/release.js +34 -0
  115. package/dist/release.js.map +1 -0
  116. package/dist/rooms-check.d.ts +90 -0
  117. package/dist/rooms-check.js +717 -0
  118. package/dist/rooms-check.js.map +1 -0
  119. package/dist/source-tree-contract.d.ts +16 -0
  120. package/dist/source-tree-contract.js +13 -0
  121. package/dist/source-tree-contract.js.map +1 -0
  122. package/dist/testing.d.ts +464 -0
  123. package/dist/testing.js +27 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/tooling/describe-game.d.ts +2 -0
  126. package/dist/tooling/describe-game.js +54 -0
  127. package/dist/tooling/describe-game.js.map +1 -0
  128. package/dist/tooling/game-session-broker.d.ts +2 -0
  129. package/dist/tooling/game-session-broker.js +28 -0
  130. package/dist/tooling/game-session-broker.js.map +1 -0
  131. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  132. package/dist/tooling/hold-runtime-host.js +931 -0
  133. package/dist/tooling/hold-runtime-host.js.map +1 -0
  134. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  135. package/dist/tooling/list-visual-scenarios.js +25 -0
  136. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  137. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  138. package/dist/tooling/managed-dev-supervisor.js +51 -0
  139. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  140. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  141. package/dist/tooling/process-scope-guard.d.ts +2 -0
  142. package/dist/tooling/process-scope-guard.js +388 -0
  143. package/dist/tooling/process-scope-guard.js.map +1 -0
  144. package/dist/tooling/process-scope-windows.ps1 +148 -0
  145. package/dist/tooling/rooms-check-device.d.ts +2 -0
  146. package/dist/tooling/rooms-check-device.js +498 -0
  147. package/dist/tooling/rooms-check-device.js.map +1 -0
  148. package/dist/tooling/run-headless-room.d.ts +2 -0
  149. package/dist/tooling/run-headless-room.js +287 -0
  150. package/dist/tooling/run-headless-room.js.map +1 -0
  151. package/dist/tooling/run-test-profile.d.ts +2 -0
  152. package/dist/tooling/run-test-profile.js +181 -0
  153. package/dist/tooling/run-test-profile.js.map +1 -0
  154. package/dist/tooling/run-visual-capture.d.ts +2 -0
  155. package/dist/tooling/run-visual-capture.js +203 -0
  156. package/dist/tooling/run-visual-capture.js.map +1 -0
  157. package/dist/tooling/seal-game-build.d.ts +2 -0
  158. package/dist/tooling/seal-game-build.js +120 -0
  159. package/dist/tooling/seal-game-build.js.map +1 -0
  160. package/dist/types-CdYrgrG_.d.ts +1036 -0
  161. package/dist/types-DyRD-ym1.d.ts +141 -0
  162. package/dist/visual.d.ts +21 -0
  163. package/dist/visual.js +219 -0
  164. package/dist/visual.js.map +1 -0
  165. package/package.json +150 -3
  166. package/src/bounded-response.ts +28 -0
  167. package/src/built-game-runtime.ts +152 -0
  168. package/src/commands.ts +40 -0
  169. package/src/context.ts +218 -0
  170. package/src/controller-protocol.ts +22 -0
  171. package/src/controller.ts +1526 -0
  172. package/src/current-room-host.ts +166 -0
  173. package/src/decision-provider.ts +102 -0
  174. package/src/dependencies.ts +176 -0
  175. package/src/dependency-install-contract.ts +12 -0
  176. package/src/dev.ts +995 -0
  177. package/src/fs-utils.ts +93 -0
  178. package/src/game-action-observation.ts +106 -0
  179. package/src/game-build-protocol.ts +72 -0
  180. package/src/game-build.ts +483 -0
  181. package/src/game-run-owner.ts +2358 -0
  182. package/src/game-run-protocol.ts +448 -0
  183. package/src/game-run-record.ts +92 -0
  184. package/src/game-run-replay.ts +95 -0
  185. package/src/game-run-watch.ts +155 -0
  186. package/src/game-session-broker.ts +793 -0
  187. package/src/game-session-operations.ts +61 -0
  188. package/src/game-session-protocol.ts +180 -0
  189. package/src/game-session-runtime.ts +861 -0
  190. package/src/game-session.ts +206 -0
  191. package/src/game-settings.ts +295 -0
  192. package/src/games.ts +262 -0
  193. package/src/harness/visual/browser.ts +100 -0
  194. package/src/harness/visual/controller-observation.ts +181 -0
  195. package/src/harness/visual/prefab-contract.ts +29 -0
  196. package/src/harness/visual/prefab-runner.ts +178 -0
  197. package/src/harness/visual/runner.ts +549 -0
  198. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  199. package/src/harness/visual/scenario-contract.ts +8 -0
  200. package/src/harness/visual/scenario-helpers.ts +67 -0
  201. package/src/harness/visual/screencast.ts +155 -0
  202. package/src/harness/visual/session.ts +400 -0
  203. package/src/harness/visual/types.ts +184 -0
  204. package/src/harness/visual.ts +7 -0
  205. package/src/headless-room-protocol.ts +112 -0
  206. package/src/headless-room.ts +222 -0
  207. package/src/helper-channel.ts +229 -0
  208. package/src/helper-scripts.ts +69 -0
  209. package/src/installed-dependencies.ts +74 -0
  210. package/src/logs.ts +67 -0
  211. package/src/managed-process-scope.ts +481 -0
  212. package/src/mcp-config.ts +262 -0
  213. package/src/node-process-environment.ts +10 -0
  214. package/src/platform-auth.ts +594 -0
  215. package/src/platform-game-analytics.ts +50 -0
  216. package/src/platform-game-app-id.ts +99 -0
  217. package/src/platform-game-media.ts +209 -0
  218. package/src/platform-games.ts +217 -0
  219. package/src/policy-artifact-contract.ts +52 -0
  220. package/src/policy-artifacts.ts +134 -0
  221. package/src/process-scope-admission.ts +50 -0
  222. package/src/process-scope-protocol.ts +66 -0
  223. package/src/process-scope.ts +327 -0
  224. package/src/quality.ts +82 -0
  225. package/src/release.ts +1683 -0
  226. package/src/rooms-check-fleet.ts +194 -0
  227. package/src/rooms-check-link.ts +138 -0
  228. package/src/rooms-check-protocol.ts +244 -0
  229. package/src/rooms-check.ts +797 -0
  230. package/src/runtime-owner-protocol.ts +218 -0
  231. package/src/source-tree-contract.ts +70 -0
  232. package/src/source-tree.ts +84 -0
  233. package/src/test-profile-process.ts +153 -0
  234. package/src/test-profile-protocol.ts +116 -0
  235. package/src/testing.ts +430 -0
  236. package/src/tooling/declaration-hook.ts +52 -0
  237. package/src/tooling/describe-game.ts +49 -0
  238. package/src/tooling/game-session-broker.ts +7 -0
  239. package/src/tooling/hold-runtime-host.ts +441 -0
  240. package/src/tooling/list-visual-scenarios.ts +21 -0
  241. package/src/tooling/load-game.ts +79 -0
  242. package/src/tooling/managed-dev-supervisor.ts +71 -0
  243. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  244. package/src/tooling/process-scope-guard.ts +213 -0
  245. package/src/tooling/process-scope-windows.ps1 +148 -0
  246. package/src/tooling/rooms-check-device.ts +493 -0
  247. package/src/tooling/run-headless-room.ts +326 -0
  248. package/src/tooling/run-test-profile.ts +190 -0
  249. package/src/tooling/run-visual-capture.ts +231 -0
  250. package/src/tooling/runtime-owner-actions.ts +65 -0
  251. package/src/tooling/seal-game-build.ts +118 -0
  252. package/src/tooling/visual-pack.ts +11 -0
  253. package/src/types.ts +928 -0
  254. package/src/visual.ts +296 -0
  255. package/src/windows-process-scopes.ts +189 -0
  256. package/src/workspace-contract.ts +32 -0
@@ -0,0 +1,493 @@
1
+ /**
2
+ * One device of `airjam rooms check`: a host or a phone in its own process,
3
+ * so the check can freeze it, kill it and start a replacement; or a load
4
+ * worker running whole rooms, so latency is measured on one clock.
5
+ */
6
+ import type { AirJamInput, AirJamInputState } from "@air-jam/sdk/core";
7
+ import {
8
+ type RoomConnector,
9
+ type StateDocument,
10
+ } from "@air-jam/sdk/room-protocol";
11
+ import {
12
+ HostRoomSession,
13
+ PhoneRoomSession,
14
+ type RoomSessionStatus,
15
+ } from "@air-jam/sdk/room-session";
16
+ import { exec } from "node:child_process";
17
+ import { isDeepStrictEqual, promisify } from "node:util";
18
+ import { CheckNetwork, createCheckConnector } from "../rooms-check-link.js";
19
+ import {
20
+ deviceCommandSchema,
21
+ sharedNow,
22
+ type DeviceCommand,
23
+ type DeviceEvent,
24
+ type DeviceLink,
25
+ type LoadResult,
26
+ type RoomTraffic,
27
+ } from "../rooms-check-protocol.js";
28
+
29
+ const controls: AirJamInput = {
30
+ move: { kind: "stick", name: "move", keepDirection: false },
31
+ jump: { kind: "button", name: "jump", mode: "pressed" },
32
+ };
33
+
34
+ /** About the size of a party game's match facts, as Bumper Brawl replicates them. */
35
+ const MATCH_FACTS = Object.fromEntries(
36
+ Array.from({ length: 8 }, (_, index) => [
37
+ `p${index + 1}`,
38
+ { name: `Player ${index + 1}`, team: index % 2, wins: 0, ready: true },
39
+ ]),
40
+ );
41
+
42
+ const report = (event: DeviceEvent): void => {
43
+ if (process.connected) process.send?.(event);
44
+ };
45
+
46
+ const grants = new Map<number, () => void>();
47
+ let nextDial = 0;
48
+
49
+ /** Waits for the check's grant to open one connection. */
50
+ const dial = () =>
51
+ new Promise<void>((resolve) => {
52
+ const id = nextDial;
53
+ nextDial += 1;
54
+ grants.set(id, resolve);
55
+ report({ type: "dial", at: sharedNow(), id });
56
+ });
57
+
58
+ const grant = (id: number) => {
59
+ const resolve = grants.get(id);
60
+ if (!resolve) throw new Error(`No connection waits for grant ${id}.`);
61
+ grants.delete(id);
62
+ resolve();
63
+ };
64
+
65
+ const network = new CheckNetwork();
66
+
67
+ const connectorFor = (link: DeviceLink, onDialing: () => void): RoomConnector =>
68
+ createCheckConnector({
69
+ url: link.url,
70
+ origin: link.origin,
71
+ network,
72
+ dial,
73
+ onDialing,
74
+ onProblem: (problem) =>
75
+ report({ type: "problem", at: sharedNow(), problem }),
76
+ });
77
+
78
+ const reportDialing = () => report({ type: "dialing", at: sharedNow() });
79
+
80
+ const run = promisify(exec);
81
+
82
+ /** One fresh credential from the check's command; hosted grants are spent once. */
83
+ const fetchCredential = async (command: string): Promise<string> => {
84
+ const { stdout } = await run(command);
85
+ const credential = stdout.trim();
86
+ if (credential === "")
87
+ throw new Error("The host credential command printed nothing.");
88
+ return credential;
89
+ };
90
+
91
+ const plainStatus = (status: RoomSessionStatus) => ({
92
+ phase: status.phase,
93
+ ...(status.phase === "closed" ? { reason: status.reason } : {}),
94
+ });
95
+
96
+ const presses = (state: AirJamInputState): number => {
97
+ const jump = state.jump;
98
+ return typeof jump === "object" && "presses" in jump ? jump.presses : 0;
99
+ };
100
+
101
+ /** A phone's thumb: the button goes down and up in turn, the stick circles. */
102
+ const createThumb = (
103
+ phone: PhoneRoomSession,
104
+ onPress: (count: number) => void,
105
+ ) => {
106
+ let count = 0;
107
+ let down = false;
108
+ let angle = 0;
109
+ return () => {
110
+ down = !down;
111
+ if (down) {
112
+ count += 1;
113
+ onPress(count);
114
+ }
115
+ angle += 0.3;
116
+ phone.sendInput({
117
+ move: { x: Math.cos(angle) * 0.8, y: Math.sin(angle) * 0.8 },
118
+ jump: { down, presses: count },
119
+ });
120
+ };
121
+ };
122
+
123
+ /** Publishes the match facts with a ticking counter and the time it was published. */
124
+ const createTicker = (
125
+ host: HostRoomSession,
126
+ onPublish: (document: MatchDocument) => void,
127
+ ) => {
128
+ let tick = 0;
129
+ return () => {
130
+ tick += 1;
131
+ const document = { tick, publishedAt: sharedNow(), players: MATCH_FACTS };
132
+ onPublish(document);
133
+ host.publish("game", document);
134
+ };
135
+ };
136
+
137
+ interface MatchDocument extends StateDocument {
138
+ readonly tick: number;
139
+ readonly publishedAt: number;
140
+ readonly players: typeof MATCH_FACTS;
141
+ }
142
+
143
+ /** Whether a phone's copy carries the match facts the host publishes with every tick. */
144
+ const carriesMatchFacts = (
145
+ document: StateDocument,
146
+ ): document is MatchDocument =>
147
+ typeof document.tick === "number" &&
148
+ isDeepStrictEqual(document.players, MATCH_FACTS);
149
+
150
+ const every = (perSecond: number, work: () => void) => {
151
+ if (perSecond <= 0) return () => {};
152
+ const timer = setInterval(work, 1000 / perSecond);
153
+ return () => clearInterval(timer);
154
+ };
155
+
156
+ let tap: (() => void) | null = null;
157
+
158
+ const runHost = async (command: Extract<DeviceCommand, { type: "host" }>) => {
159
+ const credentialCommand = command.credentialCommand;
160
+ const host = new HostRoomSession({
161
+ connector: connectorFor(command.link, reportDialing),
162
+ key: command.key,
163
+ code: command.code,
164
+ instance: command.instance,
165
+ credential: credentialCommand
166
+ ? () => fetchCredential(credentialCommand)
167
+ : undefined,
168
+ seats: command.seats,
169
+ input: controls,
170
+ heartbeat: command.heartbeat ? undefined : null,
171
+ deviceWakeEvents: null,
172
+ });
173
+ const seen = new Map<string, number>();
174
+ const reportStatus = (status: RoomSessionStatus) =>
175
+ report({
176
+ type: "status",
177
+ at: sharedNow(),
178
+ status: plainStatus(status),
179
+ code: host.code,
180
+ instance: host.instance,
181
+ hostGraceMs: host.limits.hostGraceMs,
182
+ });
183
+ reportStatus(host.status);
184
+ host.on("status", reportStatus);
185
+ host.on("seats", (seats) =>
186
+ report({
187
+ type: "seats",
188
+ at: sharedNow(),
189
+ seats: seats.map(({ id, connected }) => ({ id, connected })),
190
+ }),
191
+ );
192
+ host.on("input", ({ seat, state }) => {
193
+ const count = presses(state);
194
+ // The first count a host sees is the wrapped counter itself, so earlier
195
+ // presses cannot be told apart; the frame carrying it did arrive.
196
+ const before = seen.get(seat) ?? count - 1;
197
+ seen.set(seat, count);
198
+ for (let reached = before + 1; reached <= count; reached += 1)
199
+ report({ type: "received", at: sharedNow(), seat, presses: reached });
200
+ });
201
+ let stopTicking = () => {};
202
+ host.on("status", (status) => {
203
+ stopTicking();
204
+ if (status.phase === "open")
205
+ stopTicking = every(
206
+ command.statesPerSecond,
207
+ createTicker(host, ({ tick }) =>
208
+ report({ type: "published", at: sharedNow(), tick }),
209
+ ),
210
+ );
211
+ });
212
+ };
213
+
214
+ const runPhone = (command: Extract<DeviceCommand, { type: "phone" }>) => {
215
+ const phone = new PhoneRoomSession({
216
+ connector: connectorFor(command.link, reportDialing),
217
+ key: command.key,
218
+ code: command.code,
219
+ instance: command.instance,
220
+ input: controls,
221
+ deviceWakeEvents: null,
222
+ });
223
+ const reportStatus = (status: RoomSessionStatus) =>
224
+ report({
225
+ type: "status",
226
+ at: sharedNow(),
227
+ status: plainStatus(status),
228
+ code: phone.code,
229
+ instance: phone.instance,
230
+ seat: phone.seat ?? undefined,
231
+ });
232
+ reportStatus(phone.status);
233
+ phone.on("status", reportStatus);
234
+ phone.on("host", (present) =>
235
+ report({ type: "host", at: sharedNow(), present }),
236
+ );
237
+ phone.on("state", ({ document }) => {
238
+ if (carriesMatchFacts(document))
239
+ report({ type: "state", at: sharedNow(), tick: document.tick });
240
+ });
241
+ const step = createThumb(phone, (count) =>
242
+ report({ type: "pressed", at: sharedNow(), presses: count }),
243
+ );
244
+ tap = () => {
245
+ step();
246
+ step();
247
+ };
248
+ every(command.inputsPerSecond, step);
249
+ };
250
+
251
+ const metered =
252
+ (connector: RoomConnector, traffic: RoomTraffic): RoomConnector =>
253
+ (address, handlers) => {
254
+ const size = (data: string | Uint8Array) =>
255
+ typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
256
+ const link = connector(address, {
257
+ ...handlers,
258
+ message: (data) => {
259
+ traffic.messagesOut += 1;
260
+ traffic.bytesOut += size(data);
261
+ handlers.message(data);
262
+ },
263
+ });
264
+ return {
265
+ send: (data) => {
266
+ traffic.messagesIn += 1;
267
+ traffic.bytesIn += size(data);
268
+ link.send(data);
269
+ },
270
+ buffered: () => link.buffered(),
271
+ close: () => link.close(),
272
+ };
273
+ };
274
+
275
+ /** The first value `read` gives within the deadline, or null. */
276
+ const until = <Value>(read: () => Value | null, deadlineMs: number) =>
277
+ new Promise<Value | null>((resolve) => {
278
+ const deadline = Date.now() + deadlineMs;
279
+ const check = () => {
280
+ const value = read();
281
+ if (value !== null) resolve(value);
282
+ else if (Date.now() > deadline) resolve(null);
283
+ else setTimeout(check, 20);
284
+ };
285
+ check();
286
+ });
287
+
288
+ const wait = (milliseconds: number) =>
289
+ new Promise((resolve) => setTimeout(resolve, milliseconds));
290
+
291
+ /** Long enough for any connection to get its grant, however slowly the check paces opens. */
292
+ const GRANT_DEADLINE_MS = 30 * 60_000;
293
+ const OPEN_DEADLINE_MS = 30_000;
294
+
295
+ const runLoad = async (command: Extract<DeviceCommand, { type: "load" }>) => {
296
+ const cpuAtStart = process.cpuUsage();
297
+ const traffic: RoomTraffic = {
298
+ messagesIn: 0,
299
+ bytesIn: 0,
300
+ messagesOut: 0,
301
+ bytesOut: 0,
302
+ };
303
+ const result: Omit<LoadResult, "traffic" | "cpuMs"> = {
304
+ roomsOpened: 0,
305
+ phonesJoined: 0,
306
+ roomOpenMs: [],
307
+ phoneJoinMs: [],
308
+ inputLatencyMs: [],
309
+ pressesSent: 0,
310
+ pressesLost: 0,
311
+ stateLatencyMs: [],
312
+ phonesWithoutState: 0,
313
+ };
314
+ const stops: Array<() => void> = [];
315
+ /** Each room's phones and the last document its host published, compared once the rooms go quiet. */
316
+ const replicas: Array<{
317
+ phones: PhoneRoomSession[];
318
+ published: MatchDocument | null;
319
+ }> = [];
320
+ const sessions: Array<{ close(): void }> = [];
321
+ const pending: Array<Map<number, number>> = [];
322
+ let measuring = false;
323
+
324
+ /** One session's metered connector, and how long its first connection took to open from dialing. */
325
+ const sessionLink = () => {
326
+ const times: { dialed: number | null; opened: number | null } = {
327
+ dialed: null,
328
+ opened: null,
329
+ };
330
+ return {
331
+ connector: metered(
332
+ connectorFor(command.link, () => {
333
+ times.dialed ??= sharedNow();
334
+ }),
335
+ traffic,
336
+ ),
337
+ onStatus: (status: RoomSessionStatus) => {
338
+ if (status.phase === "open") times.opened ??= sharedNow();
339
+ },
340
+ openMs: async (): Promise<number | null> => {
341
+ const dialedAt = await until(() => times.dialed, GRANT_DEADLINE_MS);
342
+ if (dialedAt === null) return null;
343
+ const openedAt = await until(() => times.opened, OPEN_DEADLINE_MS);
344
+ return openedAt === null ? null : openedAt - dialedAt;
345
+ },
346
+ };
347
+ };
348
+
349
+ const openLoadRoom = async (room: number) => {
350
+ // Fetched before dialing, so the room's open time leaves the grant out.
351
+ const credential = command.credentialCommand
352
+ ? await fetchCredential(command.credentialCommand)
353
+ : undefined;
354
+ const hostLink = sessionLink();
355
+ const host = new HostRoomSession({
356
+ connector: hostLink.connector,
357
+ key: `load-host-${room}-${crypto.randomUUID()}`,
358
+ credential:
359
+ credential === undefined
360
+ ? undefined
361
+ : () => Promise.resolve(credential),
362
+ seats: command.phonesPerRoom,
363
+ input: controls,
364
+ deviceWakeEvents: null,
365
+ });
366
+ host.on("status", hostLink.onStatus);
367
+ sessions.push(host);
368
+ const roomOpenMs = await hostLink.openMs();
369
+ const code = host.code;
370
+ if (roomOpenMs === null || code === undefined) return;
371
+ result.roomsOpened += 1;
372
+ result.roomOpenMs.push(roomOpenMs);
373
+ const replica: (typeof replicas)[number] = { phones: [], published: null };
374
+ replicas.push(replica);
375
+ const sentBySeat = new Map<string, Map<number, number>>();
376
+ const seen = new Map<string, number>();
377
+ host.on("input", ({ seat, state }) => {
378
+ const count = presses(state);
379
+ const before = seen.get(seat) ?? count - 1;
380
+ seen.set(seat, count);
381
+ const sent = sentBySeat.get(seat);
382
+ for (let reached = before + 1; reached <= count; reached += 1) {
383
+ const at = sent?.get(reached);
384
+ if (at === undefined) continue;
385
+ sent?.delete(reached);
386
+ if (measuring) result.inputLatencyMs.push(sharedNow() - at);
387
+ }
388
+ });
389
+ await Promise.all(
390
+ Array.from({ length: command.phonesPerRoom }, async (_, index) => {
391
+ const phoneLink = sessionLink();
392
+ const phone = new PhoneRoomSession({
393
+ connector: phoneLink.connector,
394
+ key: `load-phone-${room}-${index}-${crypto.randomUUID()}`,
395
+ code,
396
+ input: controls,
397
+ deviceWakeEvents: null,
398
+ });
399
+ phone.on("status", phoneLink.onStatus);
400
+ sessions.push(phone);
401
+ phone.on("state", ({ document }) => {
402
+ if (measuring && typeof document.publishedAt === "number")
403
+ result.stateLatencyMs.push(sharedNow() - document.publishedAt);
404
+ });
405
+ const phoneJoinMs = await phoneLink.openMs();
406
+ const seat = phone.seat;
407
+ if (phoneJoinMs === null || seat === null) return;
408
+ result.phonesJoined += 1;
409
+ replica.phones.push(phone);
410
+ result.phoneJoinMs.push(phoneJoinMs);
411
+ const sent = new Map<number, number>();
412
+ sentBySeat.set(seat, sent);
413
+ pending.push(sent);
414
+ const step = createThumb(phone, (count) => {
415
+ if (!measuring) return;
416
+ result.pressesSent += 1;
417
+ sent.set(count, sharedNow());
418
+ });
419
+ await wait(Math.random() * (1000 / command.inputsPerSecond));
420
+ stops.push(every(command.inputsPerSecond, step));
421
+ }),
422
+ );
423
+ stops.push(
424
+ every(
425
+ command.statesPerSecond,
426
+ createTicker(host, (document) => {
427
+ replica.published = document;
428
+ }),
429
+ ),
430
+ );
431
+ };
432
+
433
+ // Rooms open one after another, so each host's credential is fresh when
434
+ // its connection is granted.
435
+ for (let room = 0; room < command.rooms; room += 1) await openLoadRoom(room);
436
+
437
+ measuring = true;
438
+ const trafficAtStart = { ...traffic };
439
+ await wait(command.durationMs);
440
+ measuring = false;
441
+ const measured: RoomTraffic = {
442
+ messagesIn: traffic.messagesIn - trafficAtStart.messagesIn,
443
+ bytesIn: traffic.bytesIn - trafficAtStart.bytesIn,
444
+ messagesOut: traffic.messagesOut - trafficAtStart.messagesOut,
445
+ bytesOut: traffic.bytesOut - trafficAtStart.bytesOut,
446
+ };
447
+ for (const stop of stops) stop();
448
+ await wait(1_000);
449
+ result.pressesLost = pending.reduce((lost, sent) => lost + sent.size, 0);
450
+ for (const { phones, published } of replicas)
451
+ for (const phone of phones) {
452
+ const copy = phone.channel("game");
453
+ if (!copy || !carriesMatchFacts(copy) || copy.tick !== published?.tick)
454
+ result.phonesWithoutState += 1;
455
+ }
456
+ for (const session of sessions) session.close();
457
+ const cpu = process.cpuUsage(cpuAtStart);
458
+ report({
459
+ type: "load",
460
+ at: sharedNow(),
461
+ result: {
462
+ ...result,
463
+ traffic: measured,
464
+ cpuMs: (cpu.user + cpu.system) / 1000,
465
+ },
466
+ });
467
+ };
468
+
469
+ const reportFailure = (error: unknown) =>
470
+ report({
471
+ type: "failed",
472
+ at: sharedNow(),
473
+ message: (error instanceof Error ? error.message : String(error)).trim(),
474
+ });
475
+
476
+ process.on("message", (message: unknown) => {
477
+ const command = deviceCommandSchema.parse(message);
478
+ switch (command.type) {
479
+ case "host":
480
+ return void runHost(command).catch(reportFailure);
481
+ case "phone":
482
+ return runPhone(command);
483
+ case "press":
484
+ return tap?.();
485
+ case "network":
486
+ return command.stalled ? network.stall() : network.resume();
487
+ case "dial":
488
+ return grant(command.id);
489
+ case "load":
490
+ return void runLoad(command).catch(reportFailure);
491
+ }
492
+ });
493
+ process.on("disconnect", () => process.exit(0));