@wildshard/engine 0.1.17 → 0.1.19

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 (343) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +21 -0
  5. package/lint/host-callback-syntax.mjs +2 -1
  6. package/lint/host-callbacks.mjs +3 -3
  7. package/lint/host-files.mjs +5 -4
  8. package/lint/no-base64.mjs +3 -1
  9. package/lint/ratchet.json +0 -68
  10. package/lint/ratchet.mjs +1 -4
  11. package/lint/shard-imports.mjs +6 -7
  12. package/lint/shard-source.d.mts +9 -0
  13. package/lint/shard-source.mjs +91 -0
  14. package/lint/shardfile-boundaries.mjs +10 -8
  15. package/lint/sim-closure.mjs +6 -3
  16. package/lint/wildshard-plugin.d.ts +4 -0
  17. package/lint/wildshard-plugin.js +22 -23
  18. package/package.json +25 -16
  19. package/scripts/agent-sync.mjs +27 -8
  20. package/scripts/app-build/appCook.ts +8 -2
  21. package/scripts/app-build/catalogue.ts +10 -7
  22. package/scripts/app-build/gen.ts +22 -2
  23. package/scripts/app-build/isolation.d.mts +10 -0
  24. package/scripts/app-build/isolation.mjs +47 -0
  25. package/scripts/app-build/outputProducts.d.mts +3 -0
  26. package/scripts/app-build/outputProducts.mjs +35 -0
  27. package/scripts/app-build/previousDeploy.d.mts +2 -0
  28. package/scripts/app-build/previousDeploy.mjs +10 -1
  29. package/scripts/app-build/serviceWorker.ts +10 -3
  30. package/scripts/app-build/splitOutput.mjs +4 -2
  31. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  32. package/scripts/app-build/standaloneOutput.mjs +5 -3
  33. package/scripts/app-build/titlePreloads.d.mts +8 -0
  34. package/scripts/app-build/titlePreloads.mjs +69 -0
  35. package/scripts/app-build/worldMapAtlas.ts +10 -6
  36. package/scripts/app-build-pipeline.mjs +34 -3
  37. package/scripts/built-product.mjs +1 -1
  38. package/scripts/cell-mem-bench.mjs +81 -23
  39. package/scripts/check-custom-sections-zero.mjs +1 -1
  40. package/scripts/check-devserver.mjs +3 -1
  41. package/scripts/check-models.mjs +2 -0
  42. package/scripts/check-paths.allow.json +0 -115
  43. package/scripts/check-paths.mjs +2 -2
  44. package/scripts/check-platform-ratchets.mjs +2 -3
  45. package/scripts/chromium-keychain-check.mjs +4 -2
  46. package/scripts/chromium-keychain.d.mts +1 -1
  47. package/scripts/chromium-keychain.mjs +3 -1
  48. package/scripts/ci-static.sh +1 -1
  49. package/scripts/committed-fast-checks.mjs +0 -2
  50. package/scripts/content-sw-proof.mjs +2 -1
  51. package/scripts/cook-worker.mjs +9 -3
  52. package/scripts/cook.mjs +20 -3
  53. package/scripts/devices.d.mts +4 -0
  54. package/scripts/devices.mjs +39 -0
  55. package/scripts/devserver-client.d.mts +4 -2
  56. package/scripts/devserver-client.mjs +25 -8
  57. package/scripts/docs-inputs-proof.mjs +6 -6
  58. package/scripts/doctor-proof.mjs +1 -1
  59. package/scripts/e2e-faults.mjs +159 -0
  60. package/scripts/e7-voice-staging-proof.mjs +1 -1
  61. package/scripts/gate-related-tests.mjs +1 -1
  62. package/scripts/git-source-view.mjs +1 -1
  63. package/scripts/goldens/capture.mjs +17 -5
  64. package/scripts/grid-crossing-nightly.mjs +59 -0
  65. package/scripts/grid-crossing-qa.mjs +44 -0
  66. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  67. package/scripts/grid-crossing-ratchet.mjs +52 -0
  68. package/scripts/grid-crossing-report.mjs +122 -0
  69. package/scripts/grid-crossing-stages.mjs +47 -0
  70. package/scripts/grid-crossing-tour.mjs +277 -0
  71. package/scripts/grid-crossing-walk-proof.mjs +136 -18
  72. package/scripts/host-ruler/roots.mjs +2 -2
  73. package/scripts/host-ruler.d.mts +91 -0
  74. package/scripts/host-ruler.mjs +565 -0
  75. package/scripts/live-prepush.py +3 -5
  76. package/scripts/loading-flow/benchmax.mjs +3 -1
  77. package/scripts/look-loop/test_look_loop.py +1 -38
  78. package/scripts/memory-proof.mjs +213 -0
  79. package/scripts/mmo-bots.mjs +8 -2
  80. package/scripts/net-lag-proof.mjs +219 -0
  81. package/scripts/night-market-kit-budget.mjs +2 -2
  82. package/scripts/offline-proof-rules.d.mts +5 -3
  83. package/scripts/offline-proof-rules.mjs +34 -7
  84. package/scripts/offline-proof.mjs +88 -18
  85. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  86. package/scripts/page-release/content.d.mts +9 -1
  87. package/scripts/page-release/content.mjs +131 -17
  88. package/scripts/page-release/flow.mjs +36 -10
  89. package/scripts/page-release/stamp-content.mjs +24 -0
  90. package/scripts/page-release.mjs +28 -6
  91. package/scripts/page-size.mjs +2 -1
  92. package/scripts/pin-packs.ts +1 -1
  93. package/scripts/pins.ts +4 -4
  94. package/scripts/precommit-checks.mjs +1 -7
  95. package/scripts/precommit-jobs.mjs +0 -1
  96. package/scripts/precommit-source.py +1 -9
  97. package/scripts/program-discovery.mjs +1 -1
  98. package/scripts/ring-cook.mjs +2 -1
  99. package/scripts/ring-step.ts +1 -1
  100. package/scripts/script-scenario-metrics.mjs +1 -1
  101. package/scripts/shard-output-content.d.mts +1 -1
  102. package/scripts/shard-output-content.mjs +2 -2
  103. package/scripts/shard-outputs.mjs +1 -1
  104. package/scripts/shard-public.mjs +1 -1
  105. package/scripts/shard-wire-meter.mjs +24 -9
  106. package/scripts/side-parity.mjs +4 -2
  107. package/scripts/standalone-smoke.mjs +8 -3
  108. package/scripts/tier-textures-proof.mjs +101 -0
  109. package/scripts/tier-textures.mjs +78 -0
  110. package/scripts/tile-bake-report.mjs +1 -1
  111. package/scripts/tile-bakes.mjs +1 -1
  112. package/scripts/title-assets.generated.json +2 -0
  113. package/scripts/tsconfig.json +1 -2
  114. package/scripts/vendor/basisu/LICENSE +201 -0
  115. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  116. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  117. package/scripts/vitest-push-guards.config.ts +1 -1
  118. package/scripts/vps/harden-apply.sh +4 -1
  119. package/scripts/vps/harden-prometheus.sh +176 -0
  120. package/scripts/vps/harden.sh +16 -0
  121. package/scripts/vps/rebuild.sh +18 -0
  122. package/scripts/vps/wildshard-config +84 -24
  123. package/scripts/worker-client-play.mjs +7 -2
  124. package/scripts/worker-client-proof.mjs +1 -1
  125. package/scripts/worker-client-slug.mjs +44 -0
  126. package/scripts/worktree-reap.mjs +5 -5
  127. package/src/.oxlintrc.json +3 -182
  128. package/src/client/app/entry.ts +47 -12
  129. package/src/client/engine/boot/bootCache.ts +2 -2
  130. package/src/client/engine/boot/bootTrace.ts +12 -4
  131. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  132. package/src/client/engine/boot/clearDownloads.ts +5 -2
  133. package/src/client/engine/boot/contentRead.ts +11 -0
  134. package/src/client/engine/boot/gpuFiles.ts +4 -2
  135. package/src/client/engine/boot/lastEnd.ts +99 -12
  136. package/src/client/engine/boot/parsedPages.ts +127 -58
  137. package/src/client/engine/boot/texturePack.ts +2 -2
  138. package/src/client/engine/build.d.ts +2 -0
  139. package/src/client/engine/core/Game.ts +18 -0
  140. package/src/client/engine/core/bootstrap.ts +4 -1
  141. package/src/client/engine/debug/probe.ts +18 -1
  142. package/src/client/engine/fx/LightPool.ts +41 -1
  143. package/src/client/engine/net/netPlayer.ts +19 -2
  144. package/src/client/engine/net/otherPlayers.ts +55 -8
  145. package/src/client/engine/net/predictor.ts +33 -9
  146. package/src/client/engine/net/redial.ts +29 -6
  147. package/src/client/engine/pwa/cacheNames.ts +58 -1
  148. package/src/client/engine/pwa/sw.js +53 -14
  149. package/src/client/engine/render/dataLook.ts +152 -40
  150. package/src/client/engine/render/families/detail.ts +89 -0
  151. package/src/client/engine/render/families/pbr.ts +7 -1
  152. package/src/client/engine/render/look.ts +6 -0
  153. package/src/client/engine/render/lookLight.ts +103 -11
  154. package/src/client/engine/render/lookRender.ts +105 -0
  155. package/src/client/engine/render/precompile.ts +20 -14
  156. package/src/client/engine/saves/indexed.ts +2 -2
  157. package/src/client/engine/telemetry/browserErrors.ts +28 -4
  158. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  159. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  160. package/src/client/engine/ui/debugOptions.ts +1 -1
  161. package/src/client/engine/ui/lookLightOption.ts +10 -6
  162. package/src/client/engine/ui/namePrompt.ts +7 -0
  163. package/src/client/game/boot/audio.generated.ts +114 -216
  164. package/src/client/game/boot/bytes.generated.ts +118 -238
  165. package/src/client/game/boot/placedSpawn.ts +35 -0
  166. package/src/client/game/boot/spawnDownload.ts +25 -6
  167. package/src/client/game/boot/versions.generated.ts +7 -7
  168. package/src/client/game/devScene/hook.ts +291 -0
  169. package/src/client/game/grid/area.ts +38 -0
  170. package/src/client/game/grid/cellLoading.ts +12 -2
  171. package/src/client/game/grid/live.ts +134 -12
  172. package/src/client/game/grid/liveSession.ts +47 -5
  173. package/src/client/game/grid/mapAtlas.ts +18 -4
  174. package/src/client/game/grid/menu.ts +4 -0
  175. package/src/client/game/grid/minimapBlend.ts +15 -5
  176. package/src/client/game/grid/neighbourPanels.ts +10 -1
  177. package/src/client/game/grid/oneWayIn.ts +5 -1
  178. package/src/client/game/grid/placedCards.ts +55 -0
  179. package/src/client/game/grid/placedCells.ts +233 -0
  180. package/src/client/game/grid/placedContent.ts +85 -0
  181. package/src/client/game/grid/prefetch.ts +9 -1
  182. package/src/client/game/grid/productInputs.ts +3 -1
  183. package/src/client/game/grid/productLeases.ts +4 -1
  184. package/src/client/game/grid/products.ts +8 -4
  185. package/src/client/game/grid/regionalRuntime.ts +6 -0
  186. package/src/client/game/grid/regionalWorld.ts +15 -2
  187. package/src/client/game/grid/roadCull.ts +44 -14
  188. package/src/client/game/grid/roadLook.ts +24 -15
  189. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  190. package/src/client/game/grid/roadResources.ts +24 -0
  191. package/src/client/game/grid/roadSign.worker.ts +4 -3
  192. package/src/client/game/grid/roadSignPaint.ts +16 -5
  193. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  194. package/src/client/game/grid/roadSignScale.ts +8 -0
  195. package/src/client/game/grid/roadTileBacking.ts +13 -3
  196. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  197. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  198. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  199. package/src/client/game/grid/roadTileWriter.ts +2 -1
  200. package/src/client/game/grid/screenReports.ts +39 -0
  201. package/src/client/game/grid/session.ts +29 -4
  202. package/src/client/game/grid/shardfileFar.ts +9 -3
  203. package/src/client/game/grid/softWallLook.ts +25 -8
  204. package/src/client/game/mainMenu.ts +6 -2
  205. package/src/client/game/plugin/context.ts +2 -1
  206. package/src/client/game/plugin/followedMovers.ts +7 -1
  207. package/src/client/game/quest/figures.ts +2 -0
  208. package/src/client/game/session/finish.ts +11 -1
  209. package/src/client/game/shard/titleList.ts +6 -2
  210. package/src/client/game/shardfile/assetCache.ts +4 -4
  211. package/src/client/game/shardfile/client.ts +4 -1
  212. package/src/client/game/shardfile/clientAssets.ts +9 -5
  213. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  214. package/src/client/game/shardfile/clientWater.ts +51 -9
  215. package/src/client/game/shardfile/clientWorker.ts +21 -8
  216. package/src/client/game/shardfile/look.ts +8 -3
  217. package/src/client/game/shardfile/product.ts +34 -7
  218. package/src/client/game/shardfile/productChecks.ts +2 -2
  219. package/src/client/game/shardfile/productCost.ts +2 -2
  220. package/src/client/game/shardfile/readAsset.ts +2 -2
  221. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  222. package/src/client/game/shardfile/seatGrace.ts +9 -0
  223. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  224. package/src/client/game/systems/npc/figureRows.ts +9 -0
  225. package/src/client/game/titleDeck.ts +4 -3
  226. package/src/client/host/online/doctor.ts +2 -0
  227. package/src/client/host/online/linkScreens.ts +30 -4
  228. package/src/client/host/online/shell.ts +14 -0
  229. package/src/client/host/standalone/shell.ts +4 -0
  230. package/src/cook/game/astc6Encode.ts +55 -0
  231. package/src/cook/game/astc6Wasm.ts +176 -0
  232. package/src/cook/game/cookJob.ts +30 -6
  233. package/src/cook/game/cookWorker.ts +38 -11
  234. package/src/cook/game/entryTotals.ts +51 -24
  235. package/src/cook/game/shardCook.ts +67 -9
  236. package/src/cook/game/spawnParts.ts +33 -8
  237. package/src/cook/game/tierTextures.ts +349 -0
  238. package/src/e2e/smoke/game.ts +19 -14
  239. package/src/e2e/smoke/page-globals.d.ts +9 -8
  240. package/src/e2e/smoke/template2.spec.ts +8 -7
  241. package/src/server/engine/ai/bossContenders.ts +27 -3
  242. package/src/server/engine/ai/phases.ts +1 -1
  243. package/src/server/engine/entities/creatureRefill.ts +9 -2
  244. package/src/server/engine/net/ledgerBook.ts +2 -0
  245. package/src/server/engine/net/room.ts +15 -0
  246. package/src/server/engine/sim/respawn.ts +8 -0
  247. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  248. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  249. package/src/server/game/boss/native.ts +2 -1
  250. package/src/server/game/boss/nativeWake.ts +9 -5
  251. package/src/server/game/boss/openArenaNative.ts +2 -2
  252. package/src/server/game/boss/openArenaRoom.ts +3 -1
  253. package/src/server/game/grid/room.ts +44 -3
  254. package/src/server/game/grid/simulation.ts +23 -0
  255. package/src/server/game/population/mixedRoster.ts +11 -3
  256. package/src/server/game/population/nativeBake.ts +8 -3
  257. package/src/server/game/population/nativeReturns.ts +6 -3
  258. package/src/server/game/population/roster.ts +5 -3
  259. package/src/server/game/quest/eliteDrops.ts +15 -4
  260. package/src/server/game/quest/nativeChapter.ts +1 -1
  261. package/src/server/game/quest/nativeComposition.ts +5 -1
  262. package/src/server/game/riding/nativeTaming.ts +10 -6
  263. package/src/server/game/riding/wildRefill.ts +3 -2
  264. package/src/server/game/shardfile/bossRow.ts +4 -2
  265. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  266. package/src/server/host/bake/headlessWorker.ts +1 -1
  267. package/src/server/host/dedicated/cellHost.ts +98 -16
  268. package/src/server/host/dedicated/cellProtocol.ts +16 -1
  269. package/src/server/host/dedicated/cellWorker.ts +8 -5
  270. package/src/server/host/dedicated/dedicatedRoom.ts +16 -6
  271. package/src/server/host/dedicated/gridCells.ts +15 -6
  272. package/src/server/host/dedicated/loopLag.ts +21 -0
  273. package/src/server/host/dedicated/main.ts +13 -5
  274. package/src/server/host/dedicated/packReader.ts +3 -3
  275. package/src/server/host/dedicated/placementFile.ts +4 -19
  276. package/src/server/host/dedicated/roadRoom.ts +34 -4
  277. package/src/server/host/dedicated/serverMetrics.ts +126 -0
  278. package/src/server/host/dedicated/socketPump.ts +21 -4
  279. package/src/server/host/dedicated/socketTransport.ts +2 -1
  280. package/src/server/host/dedicated/workerTable.ts +15 -4
  281. package/src/server/host/dedicated/world.ts +95 -8
  282. package/src/server/host/headless.ts +1 -1
  283. package/src/server/host/headlessRuntime.ts +1 -1
  284. package/src/server/host/standalone/roadWorld.ts +15 -3
  285. package/src/server/host/standalone/serverHost.ts +4 -1
  286. package/src/server/host/standalone/serverProduct.ts +41 -11
  287. package/src/shared/engine/ai/BossBrain.ts +8 -0
  288. package/src/shared/engine/net/deviceWord.ts +138 -0
  289. package/src/shared/engine/net/socketFrames.ts +7 -4
  290. package/src/shared/game/boss/wake.ts +6 -0
  291. package/src/shared/game/devColliders.ts +47 -0
  292. package/src/shared/game/eliteSystem.ts +8 -0
  293. package/src/shared/game/grid/allocator.ts +3 -0
  294. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  295. package/src/shared/game/grid/placementRows.ts +36 -0
  296. package/src/shared/game/plugin/bossRecord.ts +3 -2
  297. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  298. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  299. package/src/shared/game/shardfile/packReads.ts +28 -3
  300. package/src/shared/game/shardfile/serverPack.ts +9 -0
  301. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  302. package/src/shared/host/formatJsonSchema.ts +2 -2
  303. package/src/tsconfig.json +1 -27
  304. package/lint/host-reviews.json +0 -14
  305. package/lint/listed-view-code.json +0 -13
  306. package/lint/platform-pending-users.json +0 -2520
  307. package/lint/platform-pending-users.md +0 -18
  308. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  309. package/scripts/check-closed-components.d.mts +0 -7
  310. package/scripts/check-closed-components.mjs +0 -87
  311. package/scripts/g571-hosts.d.mts +0 -3
  312. package/scripts/g571-hosts.mjs +0 -54
  313. package/scripts/host-ruler/register-migrate.mjs +0 -242
  314. package/scripts/listed-view-code.d.mts +0 -7
  315. package/scripts/listed-view-code.mjs +0 -93
  316. package/scripts/look-loop/fit-lut.py +0 -142
  317. package/scripts/look-loop/palette-delta.py +0 -183
  318. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  319. package/scripts/look-loop/regions/far-reach.json +0 -225
  320. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  321. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  322. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  323. package/scripts/platform-chargebacks.d.mts +0 -9
  324. package/scripts/platform-chargebacks.mjs +0 -135
  325. package/scripts/shard-component-spans.d.mts +0 -15
  326. package/scripts/shard-component-spans.mjs +0 -18
  327. package/scripts/shard-components.d.mts +0 -16
  328. package/scripts/shard-components.mjs +0 -363
  329. package/scripts/shard-platform-hosts.d.mts +0 -2
  330. package/scripts/shard-platform-hosts.mjs +0 -93
  331. package/scripts/shard-platform-sections.d.mts +0 -2
  332. package/scripts/shard-platform-sections.mjs +0 -9
  333. package/scripts/shard-platform.d.mts +0 -76
  334. package/scripts/shard-platform.mjs +0 -1072
  335. package/src/.oxfmtrc.json +0 -48
  336. package/src/scripts/ask-new.sh +0 -29
  337. package/src/scripts/asks.mjs +0 -142
  338. package/src/scripts/herdr-prompt.sh +0 -34
  339. package/src/scripts/herdr-question-open.sh +0 -67
  340. package/src/scripts/md-wrap.mjs +0 -229
  341. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  342. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  343. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -88,6 +88,9 @@ export interface DedicatedRoomOptions {
88
88
 
89
89
  /** How `loot/personal` marks what a player has been paid. */
90
90
  const LOOT_ROW = 'loot:';
91
+ /** SERVER-CELLS SC10 (J328): a grid cell's world is never rebuilt, so what one who left was paid here is forgotten once they have stayed
92
+ * away this long, as J107's start-over forgot it after five empty minutes; one who comes back sooner (a crossing's bounce) keeps it. */
93
+ export const FORGET_PAID_MS = 300_000;
91
94
  /** A fact's entity with the seat taken out of it: a player who comes back to another seat is the same player, and the same fact (E7.4). */
92
95
  const portableEntity = (entity: string, body: string): string => entity === body ? 'player' : entity.startsWith(`${body}:`) ? entity.slice(body.length + 1) : entity;
93
96
 
@@ -179,6 +182,8 @@ export class DedicatedRoom implements CrossTarget {
179
182
  /** The lead's body leaves the world, and its seat stays for the systems bound to it. `removePlayer` refuses it. */
180
183
  /** Seats taken since this world began. */
181
184
  private joined = 0;
185
+ /** SC10: bodies that left, and when: what they were paid here is forgotten `FORGET_PAID_MS` on. */
186
+ private readonly departed = new Map<string, number>();
182
187
  /** GC15: bodies a crossing set down that haven't had a tick yet. A world that slept has no scene queries until it steps. */
183
188
  private readonly arriving = new Set<string>();
184
189
  private parkLead(): void { const { lead } = this; lead.motor.setEnabled(false); this.host.parked.add(lead.id); }
@@ -212,7 +217,7 @@ export class DedicatedRoom implements CrossTarget {
212
217
  catch (error) { return `recovery: ${String(error)}`; }
213
218
  const store = new PlayerStore(doc?.store ?? {}, () => { const own = this.seats.get(entry.device); if (own !== undefined) this.dirty(own); });
214
219
  const seat: Seat = { device: entry.device, name: entry.name, read: entry.doc, body, store, fall: this.cell.fallFloor(), transport, client: null, closeOff: null, holdEnds: null, seq: entry.seq, receipted: doc?.ledger.serial ?? 0, dirtyAt: null, savedAt: now, stand: null, version: 0 };
215
- this.seats.set(entry.device, seat); this.bodies.set(body, seat);
220
+ this.seats.set(entry.device, seat); this.bodies.set(body, seat); this.departed.delete(body);
216
221
  if (lead) this.unparkLead();
217
222
  // Two who join together would otherwise stand inside each other.
218
223
  const aside = SPAWN_ASIDE[(this.joined++) % SPAWN_ASIDE.length] ?? 0, stand = { ...spawn, x: spawn.x + aside };
@@ -224,7 +229,7 @@ export class DedicatedRoom implements CrossTarget {
224
229
  try { this.cell.owned.of(body); if (doc !== null) importPlayer(this.host, player, doc); if (at !== undefined) player.resetPose(at, at.yaw); }
225
230
  catch (error) {
226
231
  // No save or live link is installed on a failed continuation. Keep the durable copies intact.
227
- this.seats.delete(entry.device); this.bodies.delete(body); this.cell.owned.drop(body); book.seat(body, { serial: 0, rows: [] });
232
+ this.seats.delete(entry.device); this.bodies.delete(body); this.cell.owned.drop(body); book.drop(body);
228
233
  if (lead) this.clearLead(); else host.removePlayer(body);
229
234
  return `doc: ${String(error)}`;
230
235
  }
@@ -333,8 +338,8 @@ export class DedicatedRoom implements CrossTarget {
333
338
  private release(seat: Seat): void {
334
339
  this.playerRefusals.delete(seat.body);
335
340
  actRoutes(this.host).identities.delete(seat.body);
336
- this.seats.delete(seat.device); this.bodies.delete(seat.body); this.cell.owned.drop(seat.body); this.book.seat(seat.body, { serial: 0, rows: [] });
337
- if (seat.body === LEAD_SEAT) this.clearLead(); else this.host.removePlayer(seat.body);
341
+ this.seats.delete(seat.device); this.bodies.delete(seat.body); this.cell.owned.drop(seat.body); this.book.drop(seat.body);
342
+ if (seat.body === LEAD_SEAT) this.clearLead(); else { this.host.removePlayer(seat.body); this.departed.set(seat.body, this.options.now()); }
338
343
  this.options.post({ kind: 'left', device: seat.device, seats: this.seats.size });
339
344
  }
340
345
  private flushRefusals(): void {
@@ -351,10 +356,14 @@ export class DedicatedRoom implements CrossTarget {
351
356
  /** The seat goes back to how boot left it, and what it was paid goes with who earned it: the next player's bounty is their own (J105). */
352
357
  private clearLead(): void {
353
358
  actRoutes(this.host).identities.delete(LEAD_SEAT);
354
- const { ledgerDedupe } = this.host.slots, paid = `${LOOT_ROW}${LEAD_SEAT}:`;
355
- ledgerDedupe.splice(0, ledgerDedupe.length, ...ledgerDedupe.filter(row => !row.startsWith(paid)));
359
+ this.forgetPaid(LEAD_SEAT);
356
360
  importPlayer(this.host, this.lead, this.blank); this.parkLead();
357
361
  }
362
+ /** What a body was paid here goes: the next one to hold it, or its own return after a long while, earns afresh (J105, SC10). */
363
+ private forgetPaid(body: string): void {
364
+ const { ledgerDedupe } = this.host.slots, paid = `${LOOT_ROW}${body}:`;
365
+ ledgerDedupe.splice(0, ledgerDedupe.length, ...ledgerDedupe.filter(row => !row.startsWith(paid)));
366
+ }
358
367
  private step(inputs: readonly NetTickInput[]): void {
359
368
  const { host, cell } = this, routes = actRoutes(host);
360
369
  const accepted = inputs.map(input => ({ ...input, acts: input.acts.filter(act => { if (act.kind !== 'climate') return true; routes.refused++; return false; }) }));
@@ -423,6 +432,7 @@ export class DedicatedRoom implements CrossTarget {
423
432
  if (stand !== seat.stand || version !== seat.version) { seat.stand = stand; seat.version = version; this.dirty(seat); }
424
433
  if ((seat.dirtyAt !== null && now - seat.dirtyAt >= DEBOUNCE_MS) || now - seat.savedAt >= EVERY_MS) this.write(seat, 'checkpoint');
425
434
  }
435
+ for (const [body, left] of this.departed) if (now - left >= FORGET_PAID_MS) { this.departed.delete(body); this.forgetPaid(body); }
426
436
  }
427
437
  /** Everyone goes, as at SIGTERM: their last checkpoint now, and a close that says a restart is why. */
428
438
  drain(): void {
@@ -14,11 +14,14 @@ const UNPLACED_FRAME = 1;
14
14
  interface GridNames { readonly instances: readonly string[]; readonly frames: ReadonlyMap<string, number>; readonly shards: ReadonlyMap<string, string>; readonly cells: ReadonlyMap<string, string>; readonly home: string | undefined;
15
15
  /** Each taken spot (`x,z`), and the instance on it. */
16
16
  readonly spots: ReadonlyMap<string, string> }
17
- /** SA33: one cell a signed placement file names: the API's placement of a new slug (SA30), on a spot the catalogue leaves empty. */
18
- export interface PlacedCell { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number] }
17
+ /** SA33: one cell a signed placement file names: the API's placement of a new slug (SA30), on a spot the catalogue leaves empty. SA47:
18
+ * `hash` is its shardfile, for a pack the build's book lacks. */
19
+ export interface PlacedCell { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number]; readonly hash?: string }
19
20
  /** SA33: the cells placed on this running server, in the placement file's order, after the catalogue's. A restart forgets them; the
20
21
  * placement watch's first look places them again. */
21
22
  const placed: PlacedCell[] = [];
23
+ /** SA47: each placed slug's shardfile hash, when its placement named one. */
24
+ const hashes = new Map<string, string>();
22
25
  let read: { readonly from: unknown; readonly placed: number; readonly names: GridNames } | null = null;
23
26
  /** Parsed once per installed catalogue, the way a grid page assembles it, then the placed cells: frame `catalogue count + n`. */
24
27
  function gridNames(): GridNames {
@@ -39,7 +42,8 @@ function gridNames(): GridNames {
39
42
  export function placeCell(row: PlacedCell): boolean {
40
43
  const { shards, cells, spots } = gridNames(), [x, z] = row.cell, spot = `${String(x)},${String(z)}`;
41
44
  if (shards.has(row.instance)) {
42
- if (cells.get(row.slug) === row.instance && spots.get(spot) === row.instance) return false;
45
+ // SA47: a new upload moves the cell's hash; a room booted from now on (a restarted worker) opens that one.
46
+ if (cells.get(row.slug) === row.instance && spots.get(spot) === row.instance) { if (row.hash !== undefined) hashes.set(row.slug, row.hash); return false; }
43
47
  throw new Error(`${row.instance} is already placed elsewhere`);
44
48
  }
45
49
  if (!Number.isInteger(x) || !Number.isInteger(z) || Math.abs(x) > GRID_RADIUS || Math.abs(z) > GRID_RADIUS) throw new Error(`${row.instance}'s cell ${spot} is off the grid`);
@@ -47,9 +51,12 @@ export function placeCell(row: PlacedCell): boolean {
47
51
  if (cells.has(row.instance)) throw new Error(`${row.instance} is a placed shard's name`);
48
52
  const taken = spots.get(spot);
49
53
  if (taken !== undefined) throw new Error(`${spot} is ${taken}'s`);
50
- placed.push({ instance: row.instance, slug: row.slug, cell: [x, z] });
54
+ placed.push({ instance: row.instance, slug: row.slug, cell: [x, z], ...(row.hash === undefined ? {} : { hash: row.hash }) });
55
+ if (row.hash !== undefined) hashes.set(row.slug, row.hash);
51
56
  return true;
52
57
  }
58
+ /** SA47: the shardfile hash the placement named for a placed slug, so its room can open from the cook's index; undefined for any other. */
59
+ export function placedHash(slug: string): string | undefined { return hashes.get(slug); }
53
60
  let assembled: { readonly from: unknown; readonly placed: number; readonly assembly: GridAssembly } | null = null;
54
61
  /**
55
62
  * SA34a: the grid a road walks: the installed catalogue's cells and then the placed ones, so a road and its cells know a placed cell's
@@ -63,12 +70,14 @@ export function gridAssembly(placedToo = true): GridAssembly {
63
70
  return assembly;
64
71
  }
65
72
  /** What a worker thread is booted with, so its rooms name, frame and load a placed cell as the door does. */
66
- export function placedCells(): readonly PlacedCell[] { return [...placed]; }
73
+ export function placedCells(): readonly PlacedCell[] { return placed.map(row => { const hash = hashes.get(row.slug); return hash === undefined ? row : { ...row, hash }; }); }
67
74
  /** Tests only: forget every placed cell. */
68
- export function forgetPlacedCells(): void { placed.length = 0; read = null; assembled = null; }
75
+ export function forgetPlacedCells(): void { placed.length = 0; hashes.clear(); read = null; assembled = null; }
69
76
 
70
77
  /** The instance a name means: an instance stands, a grid shard's slug becomes its cell, and anything else is its own name. */
71
78
  export function cellName(name: string): string { const { shards, cells } = gridNames(); return shards.has(name) ? name : cells.get(name) ?? name; }
79
+ /** SERVER-CELLS SC5 (J328): whether a cell is the grid's, the catalogue's or a placed one. A grid cell never starts over (J107 is retired for it). */
80
+ export function gridCell(cell: string): boolean { return gridNames().shards.has(cell); }
72
81
  /** The shard a cell runs: its pack, its stores and its save rows. */
73
82
  export function cellShard(cell: string): string { return gridNames().shards.get(cell) ?? cell; }
74
83
  /** GC15: a worker's road is named for the first cell on its row, so the door finds its worker, and it is in nobody's place row. */
@@ -0,0 +1,21 @@
1
+ // SERVER-CELLS SC1: one thread's event-loop lag, read and reset once per reading. A worker sends its own in its 10 s reading; the door's
2
+ // `/metrics` (serverMetrics.ts) reads the main thread's. Kept apart from the metrics module so a worker bundle carries no metrics client.
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Node's own event-loop delay histogram.
4
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
5
+
6
+ /** One reading of a thread's loop, in ms past the sampling timer: what the loop was late by. */
7
+ export interface LoopLag { readonly p50: number; readonly p99: number; readonly max: number }
8
+ /** The sampling timer's period: Node records each period whole, so a loop on time reads this. */
9
+ const RESOLUTION_MS = 10;
10
+
11
+ /** Start sampling this thread's loop; each call answers the lag since the last one and starts the next window. */
12
+ export function loopLag(): () => LoopLag {
13
+ const delay = monitorEventLoopDelay({ resolution: RESOLUTION_MS });
14
+ delay.enable();
15
+ const late = (ns: number): number => Math.max(0, ns / 1e6 - RESOLUTION_MS);
16
+ return () => {
17
+ const read = delay.count === 0 ? { p50: 0, p99: 0, max: 0 } : { p50: late(delay.percentile(50)), p99: late(delay.percentile(99)), max: late(delay.max) };
18
+ delay.reset();
19
+ return read;
20
+ };
21
+ }
@@ -20,6 +20,7 @@ import type { ReleaseFile } from '../../../shared/host/releaseRows';
20
20
  import { fetchReleaseFile, servingRelease, ReleaseWatch } from './releaseFile';
21
21
  import { savesUrl } from './saves/pgDatabase';
22
22
  import { ServerReports } from './serverReports';
23
+ import { ServerMetrics, metricsPort } from './serverMetrics';
23
24
  import { sendSentryTest, serverSentry } from './serverSentry';
24
25
  import {PlaytestFile} from './playtest';
25
26
  import { World, type PlayerSaves, type WorkerLink } from './world';
@@ -71,11 +72,13 @@ const crossing = worldCrossing(setting('WORLD_CROSSING'));
71
72
  // SA33: where the API's signed placement file is, and its own key's public half. Both or neither; only a whole-grid world grows.
72
73
  const placementAt = setting('PLACEMENT_URL'), placementKey = setting('PLACEMENT_PUBLIC_KEY');
73
74
  if ((placementAt === undefined) !== (placementKey === undefined)) throw new Error('PLACEMENT_URL and PLACEMENT_PUBLIC_KEY go together');
75
+ // SERVER-CELLS SC1: `/metrics` on 127.0.0.1:METRICS_PORT, unset off. Made before the world opens, so every cell's boot is counted.
76
+ const metricsAt = metricsPort(process.env), metrics = metricsAt === undefined ? undefined : new ServerMetrics(log);
74
77
  const playtest=process.env['PLAYTEST']==='1'?new PlaytestFile({directory:setting('PLAYTEST_DIR')??'/var/log/wildshard',build,log,...(recordTag===undefined?{}:{tag:recordTag})}):undefined;
75
78
 
76
79
  /** One row of the table is one worker thread, started once (J182). */
77
80
  function bootWorker(slugs: readonly string[]): WorkerLink {
78
- const data: CellWorkerData = { slugs, build, origin, cache, placed: placedCells(), ...(hold === undefined ? {} : { holdMs: Number(hold) }), ...(empty === undefined ? {} : { emptyMs: Number(empty) }), ...(crossing ? { crossing } : {}),...(playtest===undefined?{}:{playtest:true}) };
81
+ const data: CellWorkerData = { slugs, build, origin, cache, placed: placedCells(), ...(hold === undefined ? {} : { holdMs: Number(hold) }), ...(empty === undefined ? {} : { emptyMs: Number(empty) }), ...(crossing ? { crossing } : {}), ...(metrics === undefined ? {} : { metrics: true }),...(playtest===undefined?{}:{playtest:true}) };
79
82
  const worker = new Worker(new URL('cellWorker.mjs', import.meta.url), { workerData: data });
80
83
  let stopped = false;
81
84
  return { send: (order, transfer = []) => { worker.postMessage(order, transfer as never); },
@@ -97,7 +100,8 @@ process.on('uncaughtException', failed);
97
100
  const trust = doorTrust(process.env);
98
101
  const world: World = await World.open({ build, cells, roads: crossing, ...worldSettings(release.channel, process.env), ...trust, secret: need('SEAT_SECRET'), saves, log, boot: bootWorker, ...(grace === undefined ? {} : { graceMs: Number(grace) }),
99
102
  // Q77: a worker that fails ends the process. systemd starts it again, clients redial, and saves stand at the last checkpoint.
100
- crashed: failed, reading: (index, row) => { reports.heard(index, row); },
103
+ crashed: failed, reading: (index, row) => { reports.heard(index, row); metrics?.reading(index, row); },
104
+ ...(metrics === undefined ? {} : { booted: (_index: number, _slug: string, ms: number) => { metrics.booted(ms); }, crossed: (ms: number, moved: boolean) => { metrics.crossed(ms, moved); } }),
101
105
  ...(playtest===undefined?{}:{playtest:row=>{playtest.append(row);}}),
102
106
  // J218: phones on 4G need TURN to reach each other's voice. Without the key, voice falls back to public STUN.
103
107
  ...(turnKey === undefined || turnToken === undefined ? {} : { voiceIce: cloudflareTurn(turnKey, turnToken) }),
@@ -119,7 +123,10 @@ stop = (code): void => { void (async (): Promise<void> => {
119
123
  process.exit(written ? code : 1);
120
124
  })(); };
121
125
  await new Promise<void>(resolve => { server.listen(port, host, resolve); });
122
- log({ at: 'server.listening', host, port, build, cells, crossing, trustProxy: trust.trustProxy, origins: trust.allowedOrigins ?? '*', serial: release.serial, epoch: release.saveEpoch, node: process.version });
126
+ metrics?.watch(world);
127
+ // A metrics port already taken never stops the game: the line says so, and the alarms see no scrape (SC3).
128
+ const metricsListening = metrics === undefined || metricsAt === undefined ? undefined : await metrics.listen(metricsAt).catch((error: unknown) => { log({ at: 'metrics.refused', port: metricsAt, error: String(error) }); return undefined; });
129
+ log({ at: 'server.listening', ...(metricsListening === undefined ? {} : { metrics: metricsListening }), host, port, build, cells, crossing, trustProxy: trust.trustProxy, origins: trust.allowedOrigins ?? '*', serial: release.serial, epoch: release.saveEpoch, node: process.version });
123
130
  // The door keeps Rapier only to read a new build's packs, so this costs no worker a tick.
124
131
  const reads: PackReads = { fetched: 0, fetchedBytes: 0, cached: 0, refused: 0 }, wasm = new URL('rapier.wasm', import.meta.url), rapier = async (): Promise<Awaited<ReturnType<typeof loadRapier>>> => loadRapier(await readFile(wasm));
125
132
  // The bundle and its packs reach disk before anyone hears a countdown, so the move costs a restart and no download. A bad hash stops here, with
@@ -136,7 +143,8 @@ const watch = new ReleaseWatch({ read: readRelease, serving: release, cells: sha
136
143
  world.beginGrace(next.engineBuild);
137
144
  } });
138
145
  // SA33: a cell the API placed opens on this running server within a look, on a worker of its own, with no grace and no restart. Its shard's
139
- // server pack must already be in this build's book: one that isn't is refused here, before any worker boots, and asked for again next look.
146
+ // server pack must be in this build's book or, SA47, in the cook's index of the shardfile hash the placement names: one in neither is
147
+ // refused here, before any worker boots, and asked for again next look.
140
148
  placements = placementAt === undefined || placementKey === undefined || listed.trim() !== WHOLE_GRID ? null : new PlacementWatch({
141
149
  read: () => fetchPlacementFile(placementAt, placementKey), channel: release.channel, ...(poll === undefined ? {} : { everyMs: Number(poll) }),
142
150
  failed: error => { log({ at: 'placement.failed', error: String(error) }); },
@@ -144,7 +152,7 @@ placements = placementAt === undefined || placementKey === undefined || listed.t
144
152
  const ready: string[] = [];
145
153
  for (const row of rows) {
146
154
  // SA34a: the pack first, so the door's placed list (and so every worker's frame numbers) holds only cells it opens.
147
- try { await readPackProduct(row.slug, build, await rapier(), { origin, cache }, reads); placeCell(row); ready.push(row.instance); }
155
+ try { await readPackProduct(row.slug, build, await rapier(), { origin, cache }, reads, row.hash); placeCell(row); ready.push(row.instance); }
148
156
  catch (error) { log({ at: 'placement.refused', instance: row.instance, slug: row.slug, error: String(error) }); }
149
157
  }
150
158
  return ready.length === 0 ? [] : world.openCells(ready);
@@ -62,7 +62,7 @@ export function packRead(options: PackReaderOptions, reads: PackReads): ServerRe
62
62
  export function readPackGrid(build: string, options: PackReaderOptions, reads: PackReads): Promise<readonly GridCollisionStrip[]> {
63
63
  return readGridCollisionPack(new URL('shards/', options.origin.endsWith('/') ? options.origin : `${options.origin}/`).href, build, packRead(options, reads));
64
64
  }
65
- /** One shard's server inputs, through its build's book. */
66
- export function readPackProduct(slug: string, build: string, rapier: Rapier, options: PackReaderOptions, reads: PackReads): Promise<HeadlessRuntimeInput> {
67
- return readServerProduct(new URL(`shards/${slug}/`, options.origin.endsWith('/') ? options.origin : `${options.origin}/`).href, () => build, packRead(options, reads), rapier);
65
+ /** One shard's server inputs, through its build's book, or for a placed slug the book lacks, the cook's index of `hash` (SA47). */
66
+ export function readPackProduct(slug: string, build: string, rapier: Rapier, options: PackReaderOptions, reads: PackReads, hash?: string): Promise<HeadlessRuntimeInput> {
67
+ return readServerProduct(new URL(`shards/${slug}/`, options.origin.endsWith('/') ? options.origin : `${options.origin}/`).href, () => build, packRead(options, reads), rapier, undefined, hash);
68
68
  }
@@ -1,31 +1,16 @@
1
1
  // SA33 (meta SHARD-AUTHORING, J314): a new slug's cell reaches a running server with no engine release. The API places a new slug (SA30) and
2
2
  // writes this file, signed with its own placement key; the release key stays engine CI's, because it vouches for the server bundle the box
3
- // runs. A placement can only add a cell on an empty spot, for a shard whose server pack this build's book already holds: it never moves the
4
- // build, the bundle or the save epoch, and a new serial here starts no grace, so players in every other cell stay connected.
5
- import * as v from 'valibot';
3
+ // runs. A placement can only add a cell on an empty spot, for a shard whose server pack this build's book holds or (SA47) the cook's index
4
+ // of the cell's shardfile `hash` names: it never moves the build, the bundle or the save epoch, and a new serial here starts no grace, so
5
+ // players in every other cell stay connected.
6
6
  import { Scope } from '@wildshard/engine/app/scope';
7
7
  import { fetchSignedText, readSigned } from './releaseFile';
8
+ import { PlacementSchema, type PlacementFile } from '@wildshard/engine/game/grid/placementRows';
8
9
  import type { PlacedCell } from './gridCells';
9
10
 
10
11
  /** How often the server looks, in ms: the release file's minute, so a placement is open inside SA33's two minutes. */
11
12
  const POLL_MS = 60_000;
12
13
  const WHAT = 'placement file';
13
- const id = v.pipe(v.string(), v.regex(/^_?[a-z0-9]+(?:-[a-z0-9]+)*$/u), v.maxLength(64));
14
- const spot = v.pipe(v.number(), v.integer());
15
-
16
- /** What a placement file says: every cell the API placed on one channel, in its grid's order. */
17
- export interface PlacementFile {
18
- /** Which kind of signed file this is, so a body can never be read as another kind's. */
19
- readonly kind: 'placement';
20
- readonly channel: 'production' | 'staging';
21
- /** Rises with every write; an older file is never believed (J179). */
22
- readonly serial: number;
23
- readonly cells: readonly PlacedCell[];
24
- }
25
- /** A placement file's body, once its signature has held. The spot's bounds are `placeCell`'s. */
26
- export const PlacementSchema: v.GenericSchema<PlacementFile> = v.object({ kind: v.literal('placement'), channel: v.picklist(['production', 'staging']), serial: v.pipe(v.number(), v.integer(), v.minValue(0)),
27
- cells: v.pipe(v.array(v.object({ instance: id, slug: id, cell: v.tuple([spot, spot]) })), v.maxLength(49)) });
28
-
29
14
  /** The file's text as what it says, under the placement key (SPKI DER in hex). */
30
15
  export function readPlacementFile(text: string, publicKey: string): PlacementFile { return readSigned(text, publicKey, PlacementSchema, WHAT); }
31
16
  /** The placement file at `url`, an `https:` bucket or a `file:` path. */
@@ -7,7 +7,7 @@ import { SimNetWorld } from '@wildshard/engine/net/simWorld';
7
7
  import type { Transport } from '@wildshard/engine/net/transport';
8
8
  import type { SimHost } from '@wildshard/engine/sim';
9
9
  import type { PlayerSim } from '@wildshard/engine/sim/playerSim';
10
- import { carryMotion } from '@wildshard/engine/game/grid/simulation';
10
+ import { carryMotion, motionOf } from '@wildshard/engine/game/grid/simulation';
11
11
  import type { GridAssembly, GridCell } from '@wildshard/engine/game/grid/assembly';
12
12
  import type { GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollision';
13
13
  import { mountedPlayerOf } from '@wildshard/engine/game/riding/native';
@@ -16,8 +16,9 @@ import { LEAD_SEAT } from '../standalone/cellWorld';
16
16
  import { HOLD_MS, type ResumeAt, type RoomNews, type SeatEntry } from './cellProtocol';
17
17
  import { crossedTo, finite, type CrossArrival, type CrossTarget } from './crossing';
18
18
  import { FallFloor } from '../standalone/fallFloor';
19
- import { placeOnRoad } from '../standalone/roadWorld';
20
- import { LEFT } from './socketPump';
19
+ import { openCellWalls, placeOnRoad } from '../standalone/roadWorld';
20
+ import { LEFT, SeatTransport } from './socketPump';
21
+ import { cellFrame } from './gridCells';
21
22
 
22
23
  /** How often a seat whose crossing is asked for asks again, and how often holds are looked at, in ticks. */
23
24
  const ASK_TICKS = 30;
@@ -54,6 +55,8 @@ export class RoadRoom implements CrossTarget {
54
55
  readonly host: SimHost;
55
56
  private readonly options: RoadRoomOptions;
56
57
  private readonly seats = new Map<string, RoadSeat>();
58
+ /** GC15 (3): cells on other workers this road crosses into (`open`), their walls down. */
59
+ private readonly opened = new Set<string>();
57
60
  /** The grid the trigger reads: the options' until a placement grows it (SA34a). */
58
61
  private assembly: GridAssembly;
59
62
  constructor(options: RoadRoomOptions) {
@@ -73,6 +76,11 @@ export class RoadRoom implements CrossTarget {
73
76
  get holding(): number { let held = 0; for (const seat of this.seats.values()) if (seat.transport === null) held++; return held; }
74
77
  holds(device: string): boolean { return this.seats.has(device); }
75
78
  bodyId(device: string): string | undefined { return this.seats.get(device)?.body; }
79
+ /** GC4: someone on this road stands within `reach` of `origin` on both axes (a cell's square grown by how near counts). */
80
+ near(origin: { readonly x: number; readonly z: number }, reach: number): boolean {
81
+ for (const seat of this.seats.values()) { const at = this.host.players.get(seat.body)?.position; if (at !== undefined && Math.abs(at.x - origin.x) <= reach && Math.abs(at.z - origin.z) <= reach) return true; }
82
+ return false;
83
+ }
76
84
  bodyOf(device: string): PlayerSim | undefined { const seat = this.seats.get(device); return seat === undefined ? undefined : this.host.players.get(seat.body); }
77
85
 
78
86
  admit(entry: SeatEntry, transport: Transport, at: ResumeAt, motion?: PlayerSim): CrossArrival | string {
@@ -100,6 +108,28 @@ export class RoadRoom implements CrossTarget {
100
108
  hello();
101
109
  this.options.post({ kind: 'seated', device: seat.device, body: seat.body, seats: this.seats.size });
102
110
  }
111
+ /** GC15 (3): cells on other workers whose entryways stand: their walls on this road come down and a walker crosses into them. */
112
+ open(cells: readonly string[]): void {
113
+ const fresh = cells.filter(cell => !this.options.hosts(cell) && !this.opened.has(cell));
114
+ openCellWalls(this.host, fresh);
115
+ for (const cell of fresh) this.opened.add(cell);
116
+ }
117
+ /**
118
+ * GC15 (3): the seat walks off the road into `to`, a cell on another worker. Its client hears `travel` (`NetRoom.handOut`), the seat goes
119
+ * from here with no hold, and its port says `out` with the walker's motion, after everything else it was sent: the door moves the socket.
120
+ * False when nothing went (no live link here).
121
+ */
122
+ handOut(device: string, to: string): boolean {
123
+ const seat = this.seats.get(device), transport = seat?.transport ?? null, player = seat === undefined ? undefined : this.host.players.get(seat.body);
124
+ if (seat === undefined || !(transport instanceof SeatTransport) || seat.client === null || player === undefined || !this.opened.has(to)) return false;
125
+ const motion = mountedPlayerOf(this.host, seat.body)?.mounted === true ? null : motionOf(player);
126
+ if (!this.net.handOut(seat.client, cellFrame(to))) return false;
127
+ mountedPlayerOf(this.host, seat.body)?.dismount();
128
+ seat.closeOff?.(); seat.closeOff = null; seat.transport = null; seat.client = null;
129
+ transport.handOut(motion);
130
+ this.release(seat);
131
+ return true;
132
+ }
103
133
  /** The seat walks off the road into `target`, a cell on this worker: its body there first, then its link (`DedicatedRoom.handOver`'s order). */
104
134
  handOver(device: string, target: CrossTarget, entry: SeatEntry, at: ResumeAt): boolean {
105
135
  const seat = this.seats.get(device), transport = seat?.transport ?? null;
@@ -155,7 +185,7 @@ export class RoadRoom implements CrossTarget {
155
185
  if (seat.transport === null || player === undefined || !finite(player.position)) continue;
156
186
  const crossed = crossedTo(this.assembly, null, player.position);
157
187
  const to = crossed?.cell?.instance ?? null;
158
- if (crossed === undefined || to === null || !this.options.hosts(to)) { seat.asked = null; continue; }
188
+ if (crossed === undefined || to === null || (!this.options.hosts(to) && !this.opened.has(to))) { seat.asked = null; continue; }
159
189
  if (seat.asked === to && this.host.state.tick - seat.askedAt < ASK_TICKS) continue;
160
190
  seat.asked = to; seat.askedAt = this.host.state.tick;
161
191
  this.options.post({ kind: 'crossing', device: seat.device, to, at: { ...crossed.at, yaw: player.yaw } });
@@ -0,0 +1,126 @@
1
+ // SERVER-CELLS SC1 (J328): the dedicated server's `/metrics`, Prometheus text on 127.0.0.1 only, on `METRICS_PORT` (unset: off). The
2
+ // process's own numbers come from the metrics client's defaults; the rest is read from what the door already hears: each worker's 10 s
3
+ // reading (tick times, ticks per second, drops, cells awake, players, its heap and its event-loop lag), each `cell.booted`, each crossing,
4
+ // and `/health`'s table for the cells each worker holds. Nothing here alters a reply or a tick, and nothing leaves loopback.
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- Its own loopback port.
6
+ import { createServer, type Server, type ServerResponse } from 'node:http';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- The port it ended up on.
8
+ import type { AddressInfo } from 'node:net';
9
+ import { Scope } from '@wildshard/engine/app/scope';
10
+ import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from '@prometheus-io/client';
11
+ import type { WorkerReading } from './cellProtocol';
12
+ import { loopLag, type LoopLag } from './loopLag';
13
+
14
+ /** Only loopback: the box's Prometheus scrapes it there (SC2), and nothing else may. */
15
+ const HOST = '127.0.0.1';
16
+ /** The main thread's lag window, as long as a worker's reading, so a second scraper never shortens it. */
17
+ const LAG_MS = 10_000;
18
+
19
+ /** `METRICS_PORT`: unset or blank is off; 0 asks for any free port (a proof's); anything else must be a port, or the server refuses to start. */
20
+ export function metricsPort(env: Readonly<Record<string, string | undefined>>): number | undefined {
21
+ const value = env['METRICS_PORT'];
22
+ if (value === undefined || value.trim() === '') return undefined;
23
+ const port = Number(value);
24
+ if (!Number.isInteger(port) || port < 0 || port > 65_535) throw new Error(`METRICS_PORT ${value} is not a port`);
25
+ return port;
26
+ }
27
+
28
+ /** What `/metrics` reads of the world when scraped: `/health`'s table, each open cell and the worker it runs on. */
29
+ export interface MetricsWorld { health: () => { readonly table: Readonly<Record<string, number>> } }
30
+
31
+ /** The server's metrics: fed by the door's callbacks, served on loopback once `listen` is called. */
32
+ export class ServerMetrics {
33
+ readonly registry: Registry = new Registry();
34
+ private world: MetricsWorld | undefined;
35
+ private server: Server | undefined;
36
+ private readonly log: (line: Record<string, unknown>) => void;
37
+ /** The main thread's lag over its last whole window. */
38
+ private mainLag: LoopLag = { p50: 0, p99: 0, max: 0 };
39
+ private readonly scope = new Scope('dedicated.metrics');
40
+ private readonly lag: Gauge<'thread' | 'quantile'>;
41
+ private readonly memory: Gauge<'thread' | 'kind'>;
42
+ private readonly tick: Gauge<'worker' | 'quantile'>;
43
+ private readonly rate: Gauge<'worker'>;
44
+ private readonly drops: Counter<'worker'>;
45
+ private readonly awake: Gauge<'worker'>;
46
+ private readonly players: Gauge<'worker'>;
47
+ private readonly held: Gauge<'worker'>;
48
+ private readonly boots: Histogram;
49
+ private readonly crossings: Histogram<'moved'>;
50
+
51
+ constructor(log: (line: Record<string, unknown>) => void) {
52
+ this.log = log;
53
+ const registers = [this.registry], readLag = loopLag();
54
+ this.scope.interval(LAG_MS, () => { this.mainLag = readLag(); });
55
+ collectDefaultMetrics({ register: this.registry });
56
+ // A metric's `collect` runs with the metric as `this`: these read the server's own state.
57
+ const mainLag = (): LoopLag => this.mainLag, table = (): Readonly<Record<string, number>> => this.world?.health().table ?? {};
58
+ this.lag = new Gauge({ name: 'wildshard_eventloop_lag_seconds', help: 'Event-loop lag per thread over its last 10 s window.', labelNames: ['thread', 'quantile'], registers,
59
+ collect() { const { p50, p99, max } = mainLag(); this.set({ thread: 'main', quantile: '0.5' }, p50 / 1000); this.set({ thread: 'main', quantile: '0.99' }, p99 / 1000); this.set({ thread: 'main', quantile: '1' }, max / 1000); } });
60
+ this.memory = new Gauge({ name: 'wildshard_thread_memory_bytes', help: 'Each thread\'s own heap, external and array-buffer bytes (a worker\'s from its last reading).', labelNames: ['thread', 'kind'], registers,
61
+ collect() { const own = process.memoryUsage(); this.set({ thread: 'main', kind: 'heap' }, own.heapUsed); this.set({ thread: 'main', kind: 'external' }, own.external); this.set({ thread: 'main', kind: 'arrayBuffers' }, own.arrayBuffers); } });
62
+ this.tick = new Gauge({ name: 'wildshard_tick_seconds', help: 'Tick time per worker over its last 10 s reading.', labelNames: ['worker', 'quantile'], registers });
63
+ this.rate = new Gauge({ name: 'wildshard_ticks_per_second', help: 'Ticks per second per worker over its last 10 s reading.', labelNames: ['worker'], registers });
64
+ this.drops = new Counter({ name: 'wildshard_tick_drops_total', help: 'Ticks a worker\'s clock dropped to catch up.', labelNames: ['worker'], registers });
65
+ this.registry.registerMetric(new Gauge({ name: 'wildshard_cells_resident', help: 'Cells open in memory, per worker (from /health\'s table).', labelNames: ['worker'], registers: [],
66
+ collect() {
67
+ this.reset();
68
+ const counts = new Map<number, number>();
69
+ for (const index of Object.values(table())) counts.set(index, (counts.get(index) ?? 0) + 1);
70
+ for (const [index, count] of counts) this.set({ worker: String(index) }, count);
71
+ } }));
72
+ this.awake = new Gauge({ name: 'wildshard_cells_awake', help: 'Cells with someone in them, ticking, per worker.', labelNames: ['worker'], registers });
73
+ this.players = new Gauge({ name: 'wildshard_players', help: 'Players seated, per worker.', labelNames: ['worker'], registers });
74
+ this.held = new Gauge({ name: 'wildshard_players_held', help: 'Bodies held for a dropped player, per worker.', labelNames: ['worker'], registers });
75
+ this.boots = new Histogram({ name: 'wildshard_cell_boot_seconds', help: 'How long a cell (or a worker\'s road) took to open: each `cell.booted`.', buckets: [0.05, 0.1, 0.25, 0.5, 1, 2, 4, 8, 16], registers });
76
+ this.crossings = new Histogram({ name: 'wildshard_crossing_seconds', help: 'A crossing, from the source\'s ask to the worker\'s answer, by whether the seat moved.', labelNames: ['moved'], buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2], registers });
77
+ }
78
+
79
+ /** The world whose table says which cells each worker holds. */
80
+ watch(world: MetricsWorld): void { this.world = world; }
81
+ /** One worker's 10 s reading. */
82
+ reading(index: number, row: WorkerReading): void {
83
+ const worker = String(index);
84
+ for (const [quantile, ms] of [['0.5', row.p50], ['0.95', row.p95], ['0.99', row.p99], ['1', row.max]] as const) this.tick.set({ worker, quantile }, ms / 1000);
85
+ this.rate.set({ worker }, row.ticksPerSecond);
86
+ this.drops.inc({ worker }, Math.max(0, row.drops));
87
+ this.awake.set({ worker }, row.awake);
88
+ this.players.set({ worker }, row.players);
89
+ this.held.set({ worker }, row.held);
90
+ const thread = `worker-${worker}`;
91
+ this.memory.set({ thread, kind: 'heap' }, row.heap);
92
+ if (row.external !== undefined) this.memory.set({ thread, kind: 'external' }, row.external);
93
+ if (row.arrayBuffers !== undefined) this.memory.set({ thread, kind: 'arrayBuffers' }, row.arrayBuffers);
94
+ if (row.lag !== undefined) for (const [quantile, ms] of [['0.5', row.lag.p50], ['0.99', row.lag.p99], ['1', row.lag.max]] as const) this.lag.set({ thread, quantile }, ms / 1000);
95
+ }
96
+ /** A cell, or a worker's road, opened in `ms`. */
97
+ booted(ms: number): void { this.boots.observe(ms / 1000); }
98
+ /** A crossing took `ms`, and the seat moved or stayed. */
99
+ crossed(ms: number, moved: boolean): void { this.crossings.observe({ moved: String(moved) }, ms / 1000); }
100
+ /** The scrape. */
101
+ text(): Promise<string> { return this.registry.metrics(); }
102
+ /** One `/metrics` answer: a scrape that fails says why, and the game never hears of it. */
103
+ private async answer(response: ServerResponse): Promise<void> {
104
+ try { const text = await this.text(); response.writeHead(200, { 'content-type': this.registry.contentType }).end(text); }
105
+ catch (error) { response.writeHead(500).end(String(error)); }
106
+ }
107
+
108
+ /** Serve `/metrics` on 127.0.0.1:`port`; answers the port it listens on. */
109
+ async listen(port: number): Promise<number> {
110
+ const server = this.server = createServer((request, response) => {
111
+ if (request.method !== 'GET' || request.url !== '/metrics') { response.writeHead(404).end(); return; }
112
+ void this.answer(response);
113
+ });
114
+ await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(port, HOST, () => { server.off('error', reject); resolve(); }); });
115
+ // Once up, a failure on this side port is a line, never a crash of the game; and it never keeps the process alive.
116
+ server.on('error', error => { this.log({ at: 'metrics.error', error: String(error) }); });
117
+ server.unref();
118
+ return (server.address() as AddressInfo).port;
119
+ }
120
+ async close(): Promise<void> {
121
+ this.scope.dispose();
122
+ const server = this.server;
123
+ this.server = undefined;
124
+ if (server !== undefined) await new Promise<void>(resolve => { server.closeAllConnections(); server.close(() => { resolve(); }); });
125
+ }
126
+ }
@@ -7,15 +7,17 @@ export const LEFT = 'left';
7
7
  /** The byte a `ready` carries to say so. */
8
8
  export const LEAVE_FLAG = 1;
9
9
  /** What crosses between a socket's thread and its room's. */
10
- type Pumped = { readonly channel: NetChannel; readonly bytes: ArrayBuffer } | { readonly close: string; readonly silentMs: number };
11
- const pumped = (value: unknown): Pumped | null => typeof value === 'object' && value !== null && ('close' in value || 'bytes' in value) ? value as Pumped : null;
10
+ // GC15 (3): `out`, from the room's end: this seat left for a cell on another worker. Everything the room said before it went first, on
11
+ // this same port, so the door moves the socket to the target's port only once the `travel` is on its way to the client.
12
+ type Pumped = { readonly channel: NetChannel; readonly bytes: ArrayBuffer } | { readonly close: string; readonly silentMs: number } | { readonly out: true; readonly motion: unknown };
13
+ const pumped = (value: unknown): Pumped | null => typeof value === 'object' && value !== null && ('close' in value || 'bytes' in value || 'out' in value) ? value as Pumped : null;
12
14
 
13
15
  /**
14
16
  * J182: the socket lives on the main thread and its cell in a worker, and this is all that joins them. `end` keeps backpressure, the
15
17
  * silence check and the keepalive, because those need the socket; the room hears the same bytes it would on any Transport. The port
16
18
  * closes with the socket, and what the room says after that goes nowhere.
17
19
  */
18
- export function pumpSocket(end: SocketTransport, port: MessagePort, now: () => number = diagnosticNow): void {
20
+ export function pumpSocket(end: SocketTransport, port: MessagePort, now: () => number = diagnosticNow, out?: (motion: unknown) => void): void {
19
21
  const off = end.onMessage((channel, bytes) => { port.postMessage({ channel, bytes }, [bytes]); });
20
22
  // E7.3: a clean quit from the menu: `ready` again, with a flag. The body goes at once.
21
23
  const quit = end.onControl((control, bytes) => { if (control === 'ready' && new Uint8Array(bytes)[0] === LEAVE_FLAG) end.close(LEFT); });
@@ -23,7 +25,11 @@ export function pumpSocket(end: SocketTransport, port: MessagePort, now: () => n
23
25
  port.onmessage = (event: MessageEvent<unknown>): void => {
24
26
  const message = pumped(event.data);
25
27
  if (message === null) return;
26
- if ('close' in message) { off(); quit(); closed(); end.close(message.close); port.close(); } else end.send(message.channel, message.bytes);
28
+ if ('out' in message) {
29
+ // GC15 (3): the room let this seat go to another worker: the socket stays open and the door points it at the target's port
30
+ off(); quit(); closed(); port.close();
31
+ if (out === undefined) end.close('retry'); else out(message.motion);
32
+ } else if ('close' in message) { off(); quit(); closed(); end.close(message.close); port.close(); } else end.send(message.channel, message.bytes);
27
33
  };
28
34
  }
29
35
 
@@ -42,6 +48,7 @@ export class SeatTransport implements Transport {
42
48
  port.onmessage = (event: MessageEvent<unknown>): void => {
43
49
  const message = pumped(event.data);
44
50
  if (message === null) return;
51
+ if ('out' in message) return;
45
52
  if ('close' in message) { this.silentMs = message.silentMs; this.ended(message.close); } else this.deliver(message.channel, message.bytes);
46
53
  };
47
54
  }
@@ -57,6 +64,16 @@ export class SeatTransport implements Transport {
57
64
  this.port.postMessage({ channel, bytes }, [bytes]);
58
65
  }
59
66
  onMessage(listener: (channel: NetChannel, bytes: ArrayBuffer) => void): () => void { this.messages.add(listener); return () => { this.messages.delete(listener); }; }
67
+ /**
68
+ * GC15 (3): this seat walks on to a cell on another worker. After everything already sent (the `travel`), the door hears `out` and
69
+ * moves the socket; this end is done, and its close listeners never hear of it: nothing closed.
70
+ */
71
+ handOut(motion: unknown): void {
72
+ if (!this.open) return;
73
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort has no origin.
74
+ this.port.postMessage({ out: true, motion });
75
+ this.open = false; this.closes.clear(); this.messages.clear();
76
+ }
60
77
  onClose(listener: (reason: string) => void): () => void { this.closes.add(listener); return () => { this.closes.delete(listener); }; }
61
78
  close(reason = 'closed'): void {
62
79
  if (!this.open) return;
@@ -1,7 +1,7 @@
1
1
  import { Scope } from '@wildshard/engine/app/scope';
2
2
  import { diagnosticNow } from '@wildshard/engine/core/clock';
3
3
  import { CLIENT_FLOOD_DEBT, CLIENT_MESSAGES_PER_TICK, MAX_CLIENT_MESSAGES, MAX_CLIENT_MESSAGE_BYTES } from '@wildshard/engine/net/room';
4
- import { channelPrefix, closeCode, closeReason, controlPrefix, decodePing, encodePong, FRAME_SKIP_BYTES, framed, PING_FLOOR_MS, SILENCE_MS, SOCKET_PING, SOCKET_PLAYTEST, SOCKET_READY, SOCKET_RELIABLE, SOCKET_UNRELIABLE, SOCKET_VOICE, STALL_CLOSE_BYTES, type SocketControl } from '@wildshard/engine/net/socketFrames';
4
+ import { channelPrefix, closeCode, closeReason, controlPrefix, decodePing, encodePong, FRAME_SKIP_BYTES, framed, PING_FLOOR_MS, SILENCE_MS, SOCKET_DEVICE, SOCKET_PING, SOCKET_PLAYTEST, SOCKET_READY, SOCKET_RELIABLE, SOCKET_UNRELIABLE, SOCKET_VOICE, STALL_CLOSE_BYTES, type SocketControl } from '@wildshard/engine/net/socketFrames';
5
5
  import type { NetChannel, Transport, TransportStats } from '@wildshard/engine/net/transport';
6
6
  import type { RawData, ServerOptions, WebSocket } from 'ws';
7
7
 
@@ -105,6 +105,7 @@ export class SocketTransport implements Transport {
105
105
  else if (prefix === SOCKET_READY) for (const listener of this.controls) listener('ready', body);
106
106
  else if (prefix === SOCKET_PLAYTEST) for (const listener of this.controls) listener('playtest', body);
107
107
  else if (prefix === SOCKET_VOICE) for (const listener of this.controls) listener('voice', body);
108
+ else if (prefix === SOCKET_DEVICE) for (const listener of this.controls) listener('device', body);
108
109
  else this.close('refused');
109
110
  }
110
111
  private ping(bytes: Buffer): void {
@@ -27,15 +27,26 @@ export function worldCrossing(value: string | undefined): boolean {
27
27
 
28
28
  /**
29
29
  * The table for the cells this server opens: one row a worker, at most `workers` rows. Only an open cell takes a row, so one cell is one
30
- * worker. Named rows go first; the rest are shared, and if the count runs out the last row takes whatever is left.
30
+ * worker. Named rows go first; the rest are shared, and if the count runs out the last row takes the named cells left over.
31
+ * GC13: the unnamed cells then move from that last row to the rows holding fewest, so no worker holds more than its share plus one.
32
+ * (Before, the last row kept them all: staging's 2 workers held Nalati alone and the other 25 cells together.) A named cell stays
33
+ * where it was, so Driftwood's crossings to Sunscar and Sky Reach stay on one worker; a crossing between workers is GC15's move.
31
34
  */
32
35
  export function workerTable(cells: readonly string[], workers: number): readonly (readonly string[])[] {
33
36
  const open = new Set(cells), named = new Set([...DEDICATED, ...SHARED.flat()]), rest = cells.filter(slug => !named.has(slug)).sort();
34
37
  const rows = [...DEDICATED.map(slug => [slug]), ...SHARED].map(row => row.filter(slug => open.has(slug))).filter(row => row.length > 0);
35
38
  const room = Math.max(1, workers - rows.length), share = Array.from({ length: room }, (): string[] => []);
36
39
  rest.forEach((slug, index) => { share[index % room]?.push(slug); });
37
- const table = [...rows, ...share.filter(row => row.length > 0)], kept = table.slice(0, Math.max(1, workers - 1)), over = table.slice(kept.length).flat();
40
+ const table = [...rows, ...share.filter(row => row.length > 0)];
38
41
  if (table.length <= workers) return table;
39
- // GC31: one worker is one row, so a crossing reaches every cell (`kept` keeps a first row whenever it can).
40
- return workers <= 1 ? [table.flat()] : [...kept, over];
42
+ // GC31: one worker is one row, so a crossing reaches every cell.
43
+ if (workers <= 1) return [table.flat()];
44
+ const kept = rows.slice(0, workers - 1).map(row => row.slice()), over = [...rows.slice(workers - 1).flat(), ...rest];
45
+ // the unnamed cells sit at the end of `over`, so the last cell is the one to move while it is unnamed
46
+ for (let moving = over.at(-1); moving !== undefined && !named.has(moving); moving = over.at(-1)) {
47
+ const lightest = kept.reduce((best, row) => (row.length < best.length ? row : best));
48
+ if (over.length <= lightest.length + 1) break;
49
+ over.pop(); lightest.push(moving);
50
+ }
51
+ return [...kept, over];
41
52
  }