@wildshard/engine 0.1.18 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/budgets/shard-size-baseline.json +10 -4
- package/index.html +6 -4
- package/lint/engine-sides.json +18 -0
- package/lint/ratchet.json +0 -68
- package/lint/ratchet.mjs +1 -4
- package/package.json +19 -15
- package/scripts/agent-sync.mjs +27 -8
- package/scripts/app-build/appCook.ts +8 -2
- package/scripts/app-build/catalogue.ts +10 -7
- package/scripts/app-build/gen.ts +33 -2
- package/scripts/app-build/isolation.d.mts +10 -0
- package/scripts/app-build/isolation.mjs +47 -0
- package/scripts/app-build/outputProducts.mjs +4 -0
- package/scripts/app-build/previousDeploy.d.mts +2 -0
- package/scripts/app-build/previousDeploy.mjs +10 -1
- package/scripts/app-build/serviceWorker.ts +10 -3
- package/scripts/app-build/splitOutput.mjs +4 -2
- package/scripts/app-build/standaloneOutput.d.mts +1 -1
- package/scripts/app-build/standaloneOutput.mjs +5 -3
- package/scripts/app-build/titlePreloads.d.mts +8 -0
- package/scripts/app-build/titlePreloads.mjs +69 -0
- package/scripts/app-build/worldMapAtlas.ts +10 -6
- package/scripts/app-build-pipeline.mjs +31 -3
- package/scripts/built-product.mjs +1 -1
- package/scripts/cell-mem-bench.mjs +83 -23
- package/scripts/check-custom-sections-zero.mjs +1 -1
- package/scripts/check-devserver.mjs +2 -0
- package/scripts/check-models.mjs +2 -0
- package/scripts/check-paths.allow.json +0 -115
- package/scripts/check-paths.mjs +2 -2
- package/scripts/check-platform-ratchets.mjs +2 -3
- package/scripts/chromium-keychain.d.mts +1 -1
- package/scripts/ci-static.sh +1 -1
- package/scripts/committed-fast-checks.mjs +0 -2
- package/scripts/content-sw-proof.mjs +2 -1
- package/scripts/cook-worker.mjs +9 -3
- package/scripts/cook.mjs +18 -5
- package/scripts/docs-inputs-proof.mjs +6 -6
- package/scripts/e7-voice-staging-proof.mjs +1 -1
- package/scripts/gate-related-tests.mjs +1 -1
- package/scripts/git-source-view.mjs +1 -1
- package/scripts/goldens/capture.mjs +17 -5
- package/scripts/grid-crossing-nightly.mjs +59 -0
- package/scripts/grid-crossing-qa.mjs +44 -0
- package/scripts/grid-crossing-ratchet.d.mts +6 -0
- package/scripts/grid-crossing-ratchet.mjs +52 -0
- package/scripts/grid-crossing-report.mjs +122 -0
- package/scripts/grid-crossing-stages.mjs +47 -0
- package/scripts/grid-crossing-tour.mjs +284 -0
- package/scripts/grid-crossing-walk-proof.mjs +126 -17
- package/scripts/host-ruler/roots.mjs +2 -2
- package/scripts/host-ruler.d.mts +91 -0
- package/scripts/host-ruler.mjs +565 -0
- package/scripts/land.mjs +2 -1
- package/scripts/live-prepush.py +3 -5
- package/scripts/loading-flow/benchmax.mjs +37 -12
- package/scripts/loading-flow/deskbench.mjs +276 -0
- package/scripts/loading-flow/stalls.d.mts +17 -3
- package/scripts/loading-flow/stalls.mjs +82 -3
- package/scripts/look-loop/test_look_loop.py +1 -38
- package/scripts/memory-proof.mjs +61 -6
- package/scripts/mmo-bots.mjs +8 -2
- package/scripts/net-lag-proof.mjs +219 -0
- package/scripts/night-market-kit-budget.mjs +2 -2
- package/scripts/nightly-model.ts +9 -6
- package/scripts/offline-proof-rules.d.mts +2 -2
- package/scripts/offline-proof-rules.mjs +15 -4
- package/scripts/offline-proof.mjs +80 -13
- package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
- package/scripts/page-release/content.d.mts +9 -1
- package/scripts/page-release/content.mjs +131 -17
- package/scripts/page-release/flow.mjs +36 -10
- package/scripts/page-release/stamp-content.mjs +24 -0
- package/scripts/page-release.mjs +28 -6
- package/scripts/page-size.mjs +2 -1
- package/scripts/parity/boot-smoke.mjs +13 -2
- package/scripts/pin-format.ts +5 -2
- package/scripts/pin-packs.ts +1 -1
- package/scripts/pins-reuse.d.mts +1 -0
- package/scripts/pins-reuse.mjs +22 -0
- package/scripts/pins.ts +4 -4
- package/scripts/precommit-checks.mjs +1 -7
- package/scripts/precommit-jobs.mjs +0 -1
- package/scripts/precommit-source.py +1 -9
- package/scripts/program-discovery.mjs +1 -1
- package/scripts/ring-cook.mjs +2 -1
- package/scripts/ring-step.ts +1 -1
- package/scripts/scratch-dir.mjs +95 -0
- package/scripts/scratch-sweep.mjs +182 -0
- package/scripts/script-scenario-metrics.mjs +1 -1
- package/scripts/shard-output-content.d.mts +1 -1
- package/scripts/shard-output-content.mjs +2 -2
- package/scripts/shard-outputs.mjs +1 -1
- package/scripts/shard-public.mjs +1 -1
- package/scripts/shard-wire-meter.mjs +24 -9
- package/scripts/side-parity.mjs +4 -2
- package/scripts/standalone-smoke.mjs +8 -3
- package/scripts/tier-textures.mjs +22 -4
- package/scripts/tile-bake-report.mjs +1 -1
- package/scripts/tile-bakes.mjs +1 -1
- package/scripts/title-assets.generated.json +2 -0
- package/scripts/tsconfig.json +2 -14
- package/scripts/vendor/basisu/LICENSE +201 -0
- package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
- package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
- package/scripts/vitest-push-guards.config.ts +1 -1
- package/scripts/vps/harden-apply.sh +4 -1
- package/scripts/vps/harden-prometheus.sh +179 -0
- package/scripts/vps/harden.sh +16 -0
- package/scripts/vps/rebuild.sh +18 -0
- package/scripts/vps/wildshard-config +6 -2
- package/scripts/worker-client-play.mjs +6 -2
- package/scripts/worktree-reap.mjs +59 -13
- package/scripts/worktree.mjs +19 -5
- package/src/.oxlintrc.json +3 -182
- package/src/client/app/entry.ts +10 -2
- package/src/client/engine/anim/rigParser.ts +2 -2
- package/src/client/engine/boot/bootCache.ts +2 -2
- package/src/client/engine/boot/bootTrace.ts +12 -4
- package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
- package/src/client/engine/boot/clearDownloads.ts +5 -2
- package/src/client/engine/boot/contentRead.ts +11 -0
- package/src/client/engine/boot/gpuFiles.ts +4 -2
- package/src/client/engine/boot/lastEnd.ts +99 -12
- package/src/client/engine/boot/texturePack.ts +2 -2
- package/src/client/engine/core/Game.ts +63 -19
- package/src/client/engine/core/gpuOnly.ts +10 -0
- package/src/client/engine/core/renderBudget.ts +134 -0
- package/src/client/engine/net/netPlayer.ts +19 -2
- package/src/client/engine/net/otherPlayers.ts +55 -8
- package/src/client/engine/net/predictor.ts +33 -9
- package/src/client/engine/net/redial.ts +68 -10
- package/src/client/engine/pwa/cacheNames.ts +58 -1
- package/src/client/engine/pwa/sw.js +41 -11
- package/src/client/engine/render/dataLook.ts +219 -44
- package/src/client/engine/render/families/detail.ts +89 -0
- package/src/client/engine/render/families/pbr.ts +9 -1
- package/src/client/engine/render/families/registry.ts +11 -2
- package/src/client/engine/render/families/sceneSurface.ts +116 -0
- package/src/client/engine/render/look.ts +12 -0
- package/src/client/engine/render/lookLight.ts +103 -11
- package/src/client/engine/render/lookRender.ts +105 -0
- package/src/client/engine/render/precompile.ts +4 -2
- package/src/client/engine/render/tiers.ts +4 -1
- package/src/client/engine/saves/indexed.ts +2 -2
- package/src/client/engine/telemetry/browserErrors.ts +24 -3
- package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
- package/src/client/engine/ui/debugOptions.ts +1 -1
- package/src/client/engine/ui/lookLightOption.ts +10 -6
- package/src/client/engine/ui/namePrompt.ts +7 -0
- package/src/client/engine/world/declaredProps.ts +5 -1
- package/src/client/engine/world/skyRig.ts +4 -1
- package/src/client/engine/world/terrainTileView.ts +64 -23
- package/src/client/game/boot/audio.generated.ts +114 -114
- package/src/client/game/boot/bytes.generated.ts +118 -220
- package/src/client/game/boot/placedSpawn.ts +35 -0
- package/src/client/game/boot/spawnDownload.ts +25 -6
- package/src/client/game/boot/versions.generated.ts +7 -5
- package/src/client/game/devScene/hook.ts +428 -0
- package/src/client/game/devScene/liveLook.ts +21 -0
- package/src/client/game/grid/cellLoading.ts +12 -2
- package/src/client/game/grid/live.ts +152 -19
- package/src/client/game/grid/liveSession.ts +53 -3
- package/src/client/game/grid/mapAtlas.ts +18 -4
- package/src/client/game/grid/minimapBlend.ts +15 -5
- package/src/client/game/grid/oneWayIn.ts +5 -1
- package/src/client/game/grid/pageEntry.ts +12 -1
- package/src/client/game/grid/placedCells.ts +114 -12
- package/src/client/game/grid/placedContent.ts +85 -0
- package/src/client/game/grid/prefetch.ts +9 -1
- package/src/client/game/grid/productInputs.ts +23 -10
- package/src/client/game/grid/productLeases.ts +4 -1
- package/src/client/game/grid/products.ts +8 -4
- package/src/client/game/grid/roadLook.ts +24 -15
- package/src/client/game/grid/roadLookPlatform.ts +4 -2
- package/src/client/game/grid/roadResources.ts +24 -0
- package/src/client/game/grid/roadSign.worker.ts +4 -3
- package/src/client/game/grid/roadSignPaint.ts +16 -5
- package/src/client/game/grid/roadSignPreparation.ts +4 -3
- package/src/client/game/grid/roadSignScale.ts +8 -0
- package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
- package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
- package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
- package/src/client/game/grid/roadTileWriter.ts +2 -1
- package/src/client/game/grid/screenReports.ts +39 -0
- package/src/client/game/grid/session.ts +32 -7
- package/src/client/game/grid/softWallLook.ts +25 -8
- package/src/client/game/mainMenu.ts +6 -2
- package/src/client/game/plugin/context.ts +2 -1
- package/src/client/game/plugin/followedMovers.ts +7 -1
- package/src/client/game/quest/figures.ts +2 -0
- package/src/client/game/session/finish.ts +9 -0
- package/src/client/game/shardfile/assetCache.ts +4 -4
- package/src/client/game/shardfile/client.ts +28 -8
- package/src/client/game/shardfile/clientAssets.ts +9 -5
- package/src/client/game/shardfile/clientLibrary.ts +1 -1
- package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
- package/src/client/game/shardfile/clientViews.ts +36 -8
- package/src/client/game/shardfile/clientWater.ts +51 -9
- package/src/client/game/shardfile/clientWorker.ts +19 -7
- package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
- package/src/client/game/shardfile/groundMerge.ts +57 -5
- package/src/client/game/shardfile/hybrid.ts +2 -0
- package/src/client/game/shardfile/look.ts +8 -3
- package/src/client/game/shardfile/product.ts +34 -7
- package/src/client/game/shardfile/productChecks.ts +2 -2
- package/src/client/game/shardfile/productCost.ts +2 -2
- package/src/client/game/shardfile/readAsset.ts +2 -2
- package/src/client/game/shardfile/reflectingWater.ts +73 -0
- package/src/client/game/shardfile/seatGrace.ts +9 -0
- package/src/client/game/shardfile/skinPlayback.ts +1 -1
- package/src/client/game/shardfile/slabLibrary.ts +115 -49
- package/src/client/game/shardfile/tileContent.ts +1 -1
- package/src/client/game/shardfile/tileDriver.ts +38 -11
- package/src/client/game/shardfile/wirePage.ts +7 -3
- package/src/client/game/shardfile/worldScenes.ts +17 -10
- package/src/client/game/systems/npc/figureRows.ts +9 -0
- package/src/client/host/online/doctor.ts +22 -7
- package/src/client/host/online/doctorView.ts +2 -0
- package/src/client/host/online/linkScreens.ts +109 -5
- package/src/client/host/online/shell.ts +13 -4
- package/src/client/host/standalone/shell.ts +40 -0
- package/src/cook/game/astc6Encode.ts +55 -0
- package/src/cook/game/astc6Wasm.ts +176 -0
- package/src/cook/game/cookJob.ts +30 -6
- package/src/cook/game/cookWorker.ts +38 -11
- package/src/cook/game/entryTotals.ts +51 -24
- package/src/cook/game/shardCook.ts +35 -7
- package/src/cook/game/spawnParts.ts +33 -8
- package/src/cook/game/tierTextures.ts +87 -14
- package/src/server/engine/ai/bossContenders.ts +27 -3
- package/src/server/engine/ai/phases.ts +1 -1
- package/src/server/engine/entities/creatureRefill.ts +9 -2
- package/src/server/engine/net/ledgerBook.ts +2 -0
- package/src/server/engine/net/room.ts +15 -0
- package/src/server/engine/sim/respawn.ts +8 -0
- package/src/server/game/boss/arenaRoomEntry.ts +5 -1
- package/src/server/game/boss/arenaRoomNative.ts +2 -0
- package/src/server/game/boss/native.ts +2 -1
- package/src/server/game/boss/nativeWake.ts +9 -5
- package/src/server/game/boss/openArenaNative.ts +2 -2
- package/src/server/game/boss/openArenaRoom.ts +3 -1
- package/src/server/game/grid/room.ts +44 -3
- package/src/server/game/grid/simulation.ts +23 -0
- package/src/server/game/population/mixedRoster.ts +11 -3
- package/src/server/game/population/nativeBake.ts +8 -3
- package/src/server/game/population/nativeReturns.ts +6 -3
- package/src/server/game/population/roster.ts +5 -3
- package/src/server/game/quest/eliteDrops.ts +18 -3
- package/src/server/game/quest/nativeChapter.ts +1 -1
- package/src/server/game/quest/nativeComposition.ts +5 -1
- package/src/server/game/riding/nativeTaming.ts +22 -7
- package/src/server/game/riding/wildRefill.ts +3 -2
- package/src/server/game/shardfile/bossRow.ts +4 -2
- package/src/server/game/shardfile/homeKeeper.ts +4 -2
- package/src/server/host/bake/headlessWorker.ts +1 -1
- package/src/server/host/dedicated/cellHost.ts +112 -18
- package/src/server/host/dedicated/cellProtocol.ts +18 -1
- package/src/server/host/dedicated/cellWorker.ts +8 -5
- package/src/server/host/dedicated/dedicatedRoom.ts +38 -11
- package/src/server/host/dedicated/gridCells.ts +15 -6
- package/src/server/host/dedicated/loopLag.ts +21 -0
- package/src/server/host/dedicated/main.ts +13 -5
- package/src/server/host/dedicated/packReader.ts +3 -3
- package/src/server/host/dedicated/placementFile.ts +3 -2
- package/src/server/host/dedicated/roadRoom.ts +34 -4
- package/src/server/host/dedicated/serverMetrics.ts +135 -0
- package/src/server/host/dedicated/socketPump.ts +21 -4
- package/src/server/host/dedicated/workerTable.ts +32 -14
- package/src/server/host/dedicated/world.ts +65 -7
- package/src/server/host/headless.ts +1 -1
- package/src/server/host/headlessRuntime.ts +1 -1
- package/src/server/host/standalone/roadWorld.ts +15 -3
- package/src/server/host/standalone/serverHost.ts +57 -8
- package/src/server/host/standalone/serverProduct.ts +48 -16
- package/src/server/host/standalone/serverRuntime.ts +1 -1
- package/src/shared/engine/ai/BossBrain.ts +8 -0
- package/src/shared/engine/core/framePacing.ts +12 -1
- package/src/shared/engine/physics/terrainTiles.ts +20 -4
- package/src/shared/game/boss/wake.ts +6 -0
- package/src/shared/game/devColliders.ts +107 -0
- package/src/shared/game/devGameplay.ts +41 -0
- package/src/shared/game/eliteSystem.ts +8 -0
- package/src/shared/game/grid/allocator.ts +3 -0
- package/src/shared/game/grid/placementRows.ts +5 -2
- package/src/shared/game/plugin/bossRecord.ts +3 -2
- package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
- package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
- package/src/shared/game/shardfile/packReads.ts +28 -3
- package/src/shared/game/shardfile/serverPack.ts +9 -0
- package/src/shared/game/systems/looks/trampleField.ts +2 -0
- package/src/shared/host/formatJsonSchema.ts +2 -2
- package/src/tsconfig.json +1 -27
- package/lint/host-reviews.json +0 -14
- package/lint/listed-view-code.json +0 -13
- package/lint/platform-pending-users.json +0 -2520
- package/lint/platform-pending-users.md +0 -18
- package/scripts/cell-mem/metrics-preload.mjs +0 -65
- package/scripts/check-closed-components.d.mts +0 -7
- package/scripts/check-closed-components.mjs +0 -87
- package/scripts/g571-hosts.d.mts +0 -3
- package/scripts/g571-hosts.mjs +0 -54
- package/scripts/host-ruler/register-migrate.mjs +0 -242
- package/scripts/listed-view-code.d.mts +0 -7
- package/scripts/listed-view-code.mjs +0 -93
- package/scripts/look-loop/fit-lut.py +0 -142
- package/scripts/look-loop/palette-delta.py +0 -183
- package/scripts/look-loop/regions/driftwood-isle.json +0 -25
- package/scripts/look-loop/regions/far-reach.json +0 -225
- package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
- package/scripts/look-loop/regions/pine-hollow.json +0 -22
- package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
- package/scripts/platform-chargebacks.d.mts +0 -9
- package/scripts/platform-chargebacks.mjs +0 -135
- package/scripts/shard-component-spans.d.mts +0 -15
- package/scripts/shard-component-spans.mjs +0 -18
- package/scripts/shard-components.d.mts +0 -16
- package/scripts/shard-components.mjs +0 -363
- package/scripts/shard-platform-hosts.d.mts +0 -2
- package/scripts/shard-platform-hosts.mjs +0 -93
- package/scripts/shard-platform-sections.d.mts +0 -2
- package/scripts/shard-platform-sections.mjs +0 -9
- package/scripts/shard-platform.d.mts +0 -76
- package/scripts/shard-platform.mjs +0 -1072
- package/src/.oxfmtrc.json +0 -48
- package/src/scripts/ask-new.sh +0 -29
- package/src/scripts/asks.mjs +0 -142
- package/src/scripts/herdr-prompt.sh +0 -34
- package/src/scripts/herdr-question-open.sh +0 -67
- package/src/scripts/md-wrap.mjs +0 -229
- /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
- /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
- /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
|
@@ -3,13 +3,15 @@
|
|
|
3
3
|
import { installAppIdentity } from '@wildshard/engine/app/identity';
|
|
4
4
|
import { Scope } from '@wildshard/engine/app/scope';
|
|
5
5
|
import { diagnosticNow } from '@wildshard/engine/core/clock';
|
|
6
|
+
import { CHUNK_HALF } from '@wildshard/engine/core/config';
|
|
6
7
|
import { ServerClock } from '@wildshard/engine/net/serverClock';
|
|
7
8
|
import type { GridAssembly } from '@wildshard/engine/game/grid/assembly';
|
|
8
9
|
import type { GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollision';
|
|
9
10
|
import type { Rapier } from '@wildshard/engine/physics/rapier';
|
|
10
11
|
import { DedicatedRoom, type DedicatedRoomRoad } from './dedicatedRoom';
|
|
11
|
-
import { cellShard, gridAssembly, placeCell, roadName } from './gridCells';
|
|
12
|
+
import { cellShard, gridAssembly, gridCell, placeCell, roadName } from './gridCells';
|
|
12
13
|
import { RoadRoom } from './roadRoom';
|
|
14
|
+
import { applyMotion } from '@wildshard/engine/game/grid/simulation';
|
|
13
15
|
import { placedStrips } from '@wildshard/engine/game/grid/voidFloor';
|
|
14
16
|
import { openRoad } from '../standalone/roadWorld';
|
|
15
17
|
import type { HeadlessRuntimeInput } from '../headlessRuntime';
|
|
@@ -17,13 +19,26 @@ import type { CellOrder, WorkerNews, WorkerReading, WorkerResident } from './cel
|
|
|
17
19
|
import { SeatTransport } from './socketPump';
|
|
18
20
|
|
|
19
21
|
/** How often a worker reads itself (E7.8). */
|
|
20
|
-
const READING_MS = 10_000;
|
|
22
|
+
export const READING_MS = 10_000;
|
|
21
23
|
/** Enough ticks for a 10 s reading, at the worker's rate. */
|
|
22
24
|
const TICKS_KEPT = 720;
|
|
23
25
|
/** The save prefix a cell's stores share. Nothing outside a cell ever reads it. */
|
|
24
26
|
const SAVE_PREFIX = 'wildshard.room.';
|
|
25
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* SERVER-CELLS SC4 (J328): the ticks a cell runs as it opens, with nobody in it, before the worker says `booted`. A world's first ticks
|
|
29
|
+
* build what it builds lazily (each creature's animation channel programs, Rapier's first step, the JIT's first pass): 25 to 30 ms on an
|
|
30
|
+
* idle Mac, and up to 668 ms on a loaded one, which every player on the worker felt when the cell's first player arrived. One second of
|
|
31
|
+
* world time at boot pays it there instead.
|
|
32
|
+
*/
|
|
33
|
+
export const WARM_TICKS = 60;
|
|
34
|
+
/**
|
|
35
|
+
* J107: a cell everyone left starts over once it has stood empty this long, on its own timer, before anyone comes back (J320). J328 (SC5)
|
|
36
|
+
* retires it for grid cells: a grid cell's world is never rebuilt, and what players spend in it comes back through its own respawns. Only
|
|
37
|
+
* a cell the grid doesn't place (a local run's `WORLD_CELLS`) still starts over.
|
|
38
|
+
*/
|
|
26
39
|
const EMPTY_MS = 300_000;
|
|
40
|
+
/** GC4: a road walker this near a cell's edge may be about to step in, so the cell does not start over under them; looked at again this often. */
|
|
41
|
+
const NEAR_M = 40, NEAR_RETRY_MS = 5000;
|
|
27
42
|
|
|
28
43
|
/** A port as `worker_threads` and a `MessageChannel` both give it. */
|
|
29
44
|
export interface CellPort { postMessage: (message: unknown, transfer?: readonly Transferable[]) => void; on?: (event: 'message', listener: (message: unknown) => void) => unknown; onmessage?: ((event: MessageEvent<unknown>) => void) | null }
|
|
@@ -36,9 +51,11 @@ export interface CellHostOptions {
|
|
|
36
51
|
/** A shard's server inputs, by its slug. */
|
|
37
52
|
readonly load: (slug: string) => Promise<HeadlessRuntimeInput>;
|
|
38
53
|
/** A proof's overrides. `roomNow` is the rooms' hold and checkpoint clock; ticks keep real time. */
|
|
39
|
-
readonly holdMs?: number; readonly emptyMs?: number; readonly roomNow?: () => number;
|
|
40
|
-
/** What this process has resident, for the reading. */
|
|
41
|
-
readonly memory: () => { readonly rss: number; readonly heapUsed: number };
|
|
54
|
+
readonly holdMs?: number; readonly emptyMs?: number; readonly roomNow?: () => number; readonly readingMs?: number;
|
|
55
|
+
/** What this process has resident, and this thread's own heap and buffers, for the reading. */
|
|
56
|
+
readonly memory: () => { readonly rss: number; readonly heapUsed: number; readonly external?: number; readonly arrayBuffers?: number };
|
|
57
|
+
/** SC1: this thread's event-loop lag since the last reading (`loopLag`), for `/metrics`. */
|
|
58
|
+
readonly lag?: () => { readonly p50: number; readonly p99: number; readonly max: number };
|
|
42
59
|
/** The worker has closed: a worker exits here. */
|
|
43
60
|
readonly closed?: () => void;
|
|
44
61
|
/** A proof's look at each room it opens, and at its road. */
|
|
@@ -67,6 +84,8 @@ function installCellIdentity(): void {
|
|
|
67
84
|
export function runCells(port: CellPort, options: CellHostOptions): { dispose: () => void } {
|
|
68
85
|
const scope = new Scope('dedicated.worker'), started = diagnosticNow(), cells = new Map<string, Cell>();
|
|
69
86
|
let clock: ServerClock | undefined, disposed = false, ready = false, ticks: number[] = [], ticked = 0, readAt = started, dropsAt = 0;
|
|
87
|
+
/** SC8: each awake cell's own tick time since the last reading (ms summed, ticks counted), so a bench can weigh cells by awake cost. */
|
|
88
|
+
let spent = new Map<string, { ms: number; ticks: number }>();
|
|
70
89
|
const post = (news: WorkerNews): void => { port.postMessage(news); };
|
|
71
90
|
const fail = (error: unknown): void => { clock?.pause(); post({ kind: 'failed', reason: error instanceof Error ? error.message : String(error) }); };
|
|
72
91
|
// GC15: the road this worker hosts, once its cells are open, and what its cells need of it.
|
|
@@ -84,14 +103,27 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
84
103
|
/** A cell on this worker, or its road, by name. */
|
|
85
104
|
const named = (name: string): Cell | RoadRoom | undefined => road !== undefined && road.name === name ? road : cells.get(name);
|
|
86
105
|
const emptyMs = options.emptyMs ?? EMPTY_MS;
|
|
106
|
+
/** GC15 (3): cells a seat from another worker's road is arriving in: none starts over meanwhile (review SHOULD). */
|
|
107
|
+
const arrivals = new Set<Cell>();
|
|
108
|
+
/** Set by `drain`: the worker is closing, so an arrival is refused (the client retries on the next one). */
|
|
109
|
+
let drained = false;
|
|
87
110
|
/** `startOver`, once it is made below: a start-over opens a cell, and a cell's room says when it emptied. */
|
|
88
111
|
const later = { startOver: (_cell: Cell, _since: number): void => undefined };
|
|
89
112
|
/** Someone stood in this world: it has something to start over from. A refused seat never got this far. */
|
|
113
|
+
/** SC10 (J328): when each room last had nobody in it, from its boot or its last leave. */
|
|
114
|
+
const asleep = new Map<DedicatedRoom, number>();
|
|
115
|
+
/** SC10: a room's first seat after empty time: its world took no ticks meanwhile and is never rebuilt, so it spends the time now. */
|
|
116
|
+
const woke = (room: DedicatedRoom): void => {
|
|
117
|
+
const since = asleep.get(room); asleep.delete(room);
|
|
118
|
+
const seconds = since === undefined ? 0 : (diagnosticNow() - since) / 1000;
|
|
119
|
+
if (seconds >= 1) room.host.events.emit('world.slept', { seconds });
|
|
120
|
+
};
|
|
90
121
|
const used = (slug: string, room: DedicatedRoom): void => { const cell = cells.get(slug); if (cell !== undefined && cell.room === room) cell.used = true; };
|
|
91
|
-
/** J107 on J320's terms: the last seat left this cell's world, so it starts over once it has stood empty `emptyMs`, nobody waiting on it.
|
|
122
|
+
/** J107 on J320's terms: the last seat left this cell's world, so it starts over once it has stood empty `emptyMs`, nobody waiting on it.
|
|
123
|
+
* SC5 (J328): never a grid cell's. */
|
|
92
124
|
const emptied = (slug: string, room: DedicatedRoom): void => {
|
|
93
125
|
const cell = cells.get(slug);
|
|
94
|
-
if (cell === undefined || cell.room !== room || disposed) return;
|
|
126
|
+
if (cell === undefined || cell.room !== room || disposed || gridCell(slug)) return;
|
|
95
127
|
const since = cell.emptySince = diagnosticNow();
|
|
96
128
|
if (cell.used) scope.timeout(emptyMs, () => { later.startOver(cell, since); });
|
|
97
129
|
};
|
|
@@ -100,32 +132,58 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
100
132
|
const shard = cellShard(slug), begun = diagnosticNow(), input = await options.load(shard), onto = seams(slug);
|
|
101
133
|
rapier ??= input.rapier;
|
|
102
134
|
const room: DedicatedRoom = await DedicatedRoom.boot({ slug: shard, cell: slug, build: options.build, bootId: options.bootId(), input, now: options.roomNow ?? diagnosticNow, ...(onto === undefined ? {} : { road: onto }),
|
|
103
|
-
post: news => {
|
|
135
|
+
post: news => {
|
|
136
|
+
if (news.kind === 'seated') { if (news.seats === 1) woke(room); used(slug, room); } else if (news.kind === 'left' && news.seats === 0) { asleep.set(room, diagnosticNow()); emptied(slug, room); }
|
|
137
|
+
post({ ...news, slug });
|
|
138
|
+
},
|
|
104
139
|
reports: { file: report => { post({ kind: 'report', slug, report }); } }, ...(options.holdMs === undefined ? {} : { holdMs: options.holdMs }),...(options.playtest===true?{playtest:row=>{post({kind:'playtest',slug,row});}}:{}) });
|
|
140
|
+
// SC4: its first ticks now, while nobody is in it, not on its first player's arrival.
|
|
141
|
+
for (let tick = 0; tick < WARM_TICKS; tick++) room.tick();
|
|
142
|
+
asleep.set(room, diagnosticNow());
|
|
105
143
|
post({ kind: 'cell', slug, ms: diagnosticNow() - begun });
|
|
106
144
|
options.booted?.(slug, room);
|
|
107
145
|
return room;
|
|
108
146
|
};
|
|
109
147
|
const step = (): void => {
|
|
110
148
|
const begun = diagnosticNow();
|
|
111
|
-
try {
|
|
149
|
+
try {
|
|
150
|
+
for (const { slug, room } of cells.values()) {
|
|
151
|
+
if (room.taken === 0) continue;
|
|
152
|
+
const at = diagnosticNow();
|
|
153
|
+
room.tick();
|
|
154
|
+
const own = spent.get(slug) ?? { ms: 0, ticks: 0 };
|
|
155
|
+
own.ms += diagnosticNow() - at; own.ticks++; spent.set(slug, own);
|
|
156
|
+
}
|
|
157
|
+
if (road !== undefined && road.taken > 0) road.tick();
|
|
158
|
+
} catch (error) { fail(error); return; }
|
|
112
159
|
ticks.push(diagnosticNow() - begun); ticked++;
|
|
113
160
|
if (ticks.length > TICKS_KEPT) ticks.shift();
|
|
114
161
|
};
|
|
115
162
|
const reading = (): void => {
|
|
116
163
|
const now = diagnosticNow(), sorted = ticks.slice().sort((a, b) => a - b), rooms = [...cells.values()].map(cell => cell.room), memory = options.memory();
|
|
117
164
|
const sum = (read: (room: DedicatedRoom) => number): number => rooms.reduce((total, room) => total + read(room), 0);
|
|
118
|
-
|
|
165
|
+
// SC1: a seat on this worker's road is a player too, though the road is no cell.
|
|
166
|
+
const onRoad = road === undefined ? 0 : road.taken - road.holding, heldOnRoad = road?.holding ?? 0;
|
|
167
|
+
const row: WorkerReading = { cells: rooms.length, awake: rooms.filter(room => room.taken > 0).length, players: sum(room => room.taken - room.holding) + onRoad, held: sum(room => room.holding) + heldOnRoad, ticks: ticked, ticksPerSecond: ticks.length / ((now - readAt) / 1000),
|
|
119
168
|
p50: percentile(sorted, 0.5), p95: percentile(sorted, 0.95), p99: percentile(sorted, 0.99), max: sorted.at(-1) ?? 0, drops: (clock?.drops ?? 0) - dropsAt, rss: memory.rss, heap: memory.heapUsed,
|
|
120
|
-
refused: sum(room => room.net.stats.refused), dropped: sum(room => room.net.stats.dropped), frameBytes: sum(room => room.net.stats.frameBytes), eventBytes: sum(room => room.net.stats.eventBytes)
|
|
121
|
-
|
|
169
|
+
refused: sum(room => room.net.stats.refused), dropped: sum(room => room.net.stats.dropped), frameBytes: sum(room => room.net.stats.frameBytes), eventBytes: sum(room => room.net.stats.eventBytes),
|
|
170
|
+
...(spent.size === 0 ? {} : { cellMs: Object.fromEntries([...spent].map(([slug, own]) => [slug, own.ms / own.ticks])) }),
|
|
171
|
+
...(memory.external === undefined ? {} : { external: memory.external }), ...(memory.arrayBuffers === undefined ? {} : { arrayBuffers: memory.arrayBuffers }), ...(options.lag === undefined ? {} : { lag: options.lag() }) };
|
|
172
|
+
readAt = now; dropsAt = clock?.drops ?? 0; ticks = []; spent = new Map();
|
|
122
173
|
post({ kind: 'reading', reading: row });
|
|
123
174
|
};
|
|
124
175
|
/** One start-over at a time on this worker: each boot stalls the clock of every other cell here, so they never pile up. */
|
|
125
176
|
let overs: Promise<void> = Promise.resolve();
|
|
126
177
|
/** The fresh world, swapped in while the cell is still empty. One that fails keeps the old world and says so; the worker plays on. */
|
|
178
|
+
/** GC4: a walker on this worker's road near the cell's edge, or a seat arriving from another worker's road, may step in now. */
|
|
179
|
+
const walkerNear = (cell: Cell): boolean => {
|
|
180
|
+
const origin = crossing?.assembly.cells.find(row => [cell.slug].includes(row.instance))?.origin;
|
|
181
|
+
return arrivals.has(cell) || (origin !== undefined && road?.near(origin, CHUNK_HALF + NEAR_M) === true);
|
|
182
|
+
};
|
|
127
183
|
const restart = async (cell: Cell): Promise<void> => {
|
|
128
184
|
if (disposed || cell.room.taken > 0) return;
|
|
185
|
+
// review SHOULD: a start-over queued behind others looks again when its turn comes, since a walker may have come near meanwhile
|
|
186
|
+
if (walkerNear(cell)) { const since = cell.emptySince; scope.timeout(NEAR_RETRY_MS, () => { later.startOver(cell, since); }); return; }
|
|
129
187
|
try {
|
|
130
188
|
const old = cell.room, room = await open(cell.slug);
|
|
131
189
|
if (disposed) { room.dispose(); return; }
|
|
@@ -137,6 +195,8 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
137
195
|
if (disposed || cell.waking !== null || !cell.used || cell.room.taken > 0 || cell.emptySince !== since) return;
|
|
138
196
|
const left = emptyMs - (diagnosticNow() - since);
|
|
139
197
|
if (left > 0) { scope.timeout(left, () => { later.startOver(cell, since); }); return; }
|
|
198
|
+
// GC4: never boot a cell under a walker heading back to it: while someone on the road stands within NEAR_M of its edge, look again later
|
|
199
|
+
if (walkerNear(cell)) { scope.timeout(NEAR_RETRY_MS, () => { later.startOver(cell, since); }); return; }
|
|
140
200
|
const job = overs.then(() => restart(cell)).finally(() => { if (cell.waking === job) cell.waking = null; });
|
|
141
201
|
cell.waking = job; overs = job;
|
|
142
202
|
};
|
|
@@ -196,6 +256,29 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
196
256
|
const moved = source.handOver(entry.device, target, entry, at);
|
|
197
257
|
post({ kind: 'crossed', device: entry.device, name: entry.name, from: fromSlug, to: toSlug, moved, stays: source.holds(entry.device), body: moved ? target.bodyId(entry.device) ?? entry.body : entry.body });
|
|
198
258
|
};
|
|
259
|
+
/**
|
|
260
|
+
* GC15 (3): a seat another worker's road let go walks into cell `to` here, on the socket the door moved to `port`: its body first, at `at`
|
|
261
|
+
* with the walker's motion, then the room hears the client's hello again and welcomes it (the client heard `travel` first).
|
|
262
|
+
*/
|
|
263
|
+
const arrive = async (order: Extract<CellOrder, { kind: 'arrive' }>): Promise<void> => {
|
|
264
|
+
const { kind: _kind, from, to: slug, at, port: seatPort, hello, motion, ...entry } = order, cell = cells.get(slug);
|
|
265
|
+
// review MUST: the port's transport is made after the wait, as `seat`'s is: a close meanwhile stays queued on the port for it
|
|
266
|
+
const refuse = (made?: SeatTransport): void => { (made ?? new SeatTransport(seatPort)).close('retry'); post({ kind: 'crossed', device: entry.device, name: entry.name, from, to: slug, moved: false, stays: false, body: entry.body }); };
|
|
267
|
+
if (cell !== undefined) arrivals.add(cell);
|
|
268
|
+
try {
|
|
269
|
+
// review SHOULDs: a drained worker seats no one, and a cell that already holds this device keeps that body
|
|
270
|
+
if (cell === undefined || drained || !await settled(cell) || drained || cell.room.holds(entry.device)) { refuse(); return; }
|
|
271
|
+
const transport = new SeatTransport(seatPort), arrived = cell.room.admit(entry, transport, at);
|
|
272
|
+
if (typeof arrived === 'string') { refuse(transport); return; }
|
|
273
|
+
const player = cell.room.host.players.get(arrived.body);
|
|
274
|
+
if (motion !== null && player !== undefined) applyMotion(motion, player);
|
|
275
|
+
const client = cell.room.net.join(transport, cell.room.sim.playerOf(arrived.body));
|
|
276
|
+
transport.deliver('reliable', hello);
|
|
277
|
+
cell.room.net.travelled(client);
|
|
278
|
+
const moved = arrived.land(cell.room.net.live(client) ? client : null);
|
|
279
|
+
post({ kind: 'crossed', device: entry.device, name: entry.name, from, to: slug, moved, stays: false, body: cell.room.bodyId(entry.device) ?? entry.body });
|
|
280
|
+
} finally { if (cell !== undefined) arrivals.delete(cell); }
|
|
281
|
+
};
|
|
199
282
|
const handle = (order: CellOrder): void => {
|
|
200
283
|
if (order.kind === 'close') { dispose(); return; }
|
|
201
284
|
// MP4.1: a line from the world reaches each awake cell here but the one that said it. A cell asleep or starting over hears nothing.
|
|
@@ -206,8 +289,12 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
206
289
|
return;
|
|
207
290
|
}
|
|
208
291
|
if (!ready) { fail(new Error('A worker was told something before it booted')); return; }
|
|
209
|
-
if (order.kind === 'drain') { clock?.pause(); for (const { room } of cells.values()) room.drain(); road?.drain(); post({ kind: 'drained' }); return; }
|
|
292
|
+
if (order.kind === 'drain') { drained = true; clock?.pause(); for (const { room } of cells.values()) room.drain(); road?.drain(); post({ kind: 'drained' }); return; }
|
|
210
293
|
if (order.kind === 'cross') { cross(order).catch(fail); return; }
|
|
294
|
+
// GC15 (3): crossings between workers, and which cells on the others a walker can stand in
|
|
295
|
+
if (order.kind === 'open') { road?.open(order.cells); return; }
|
|
296
|
+
if (order.kind === 'handOut') { const out = road !== undefined && road.name === order.from && road.handOut(order.device, order.to); if (!out) post({ kind: 'handedOut', device: order.device, from: order.from, out }); return; }
|
|
297
|
+
if (order.kind === 'arrive') { arrive(order).catch(fail); return; }
|
|
211
298
|
if (order.kind === 'place') { placing = placing.then(() => place(order)); return; }
|
|
212
299
|
const cell = named(order.slug);
|
|
213
300
|
if (cell === undefined) { fail(new Error(`${order.slug} is not on this worker`)); return; }
|
|
@@ -219,8 +306,14 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
219
306
|
void (async (): Promise<void> => {
|
|
220
307
|
const first = options.slugs[0];
|
|
221
308
|
// SA34a: a worker booted after a placement (its `placed`) lays the placed cells out from the start.
|
|
222
|
-
//
|
|
223
|
-
|
|
309
|
+
// ROAD-RESIDENT RR4 (Jake 11-13 ~10:35: crossing always on; replaces GC28's lone cells): a book with no grid pack reads no
|
|
310
|
+
// strips, so there is no road to stand on. The worker refuses its boot: `/health` never comes up and `wildshard-config`'s
|
|
311
|
+
// rollback keeps the last good server, instead of a server whose players can't leave their cell (the `road.pack` line says 0).
|
|
312
|
+
if (options.road !== undefined && first !== undefined) {
|
|
313
|
+
const assembly = gridAssembly(), strips = await options.road(), placed = placedStrips(assembly, gridAssembly(false));
|
|
314
|
+
if (strips.length === 0) throw new Error('No road: the grid pack read 0 strips (a crossing worker needs its road)');
|
|
315
|
+
crossing = { name: roadName(first), assembly, strips: [...strips, ...placed.strips], seams: placed.seams };
|
|
316
|
+
}
|
|
224
317
|
for (const slug of options.slugs) { const room = await open(slug); if (disposed) return; cells.set(slug, { slug, room, emptySince: diagnosticNow(), used: false, waking: null }); }
|
|
225
318
|
if (crossing !== undefined && rapier !== undefined) {
|
|
226
319
|
const { name, assembly, strips } = crossing, begun = diagnosticNow();
|
|
@@ -233,8 +326,9 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
|
|
|
233
326
|
ready = true; readAt = diagnosticNow();
|
|
234
327
|
clock = new ServerClock({ now: diagnosticNow, wait: (ms, run) => { const timer = scope.timeout(ms, run); return () => { scope.cancelTimer(timer); }; }, step });
|
|
235
328
|
clock.start();
|
|
236
|
-
scope.interval(READING_MS, reading);
|
|
237
|
-
|
|
329
|
+
scope.interval(options.readingMs ?? READING_MS, reading);
|
|
330
|
+
// GC15 (3): this worker's grid cells a walker off another worker's road can stand in (GC30's entryway ground)
|
|
331
|
+
post({ kind: 'booted', ms: diagnosticNow() - started, resident: resident(), ...(road === undefined ? {} : { stands: [...cells.keys()].filter(enterable) }) });
|
|
238
332
|
})().catch(fail);
|
|
239
333
|
return { dispose };
|
|
240
334
|
}
|
|
@@ -3,6 +3,7 @@ import type { PlayerDoc } from './playerDoc';
|
|
|
3
3
|
import type { SaveReceipt, SaveWrite } from './saves/saveStore';
|
|
4
4
|
import type {PlaytestHit} from './playtest';
|
|
5
5
|
import type { PlacedCell } from './gridCells';
|
|
6
|
+
import type { MotionSnapshot } from '@wildshard/engine/game/grid/simulation';
|
|
6
7
|
|
|
7
8
|
// J182: what the door and a cell worker say to each other. Sockets stay with the door, and a seat's bytes go through its own port.
|
|
8
9
|
|
|
@@ -36,6 +37,15 @@ export type CellOrder =
|
|
|
36
37
|
* squares, their strips, and walls round any it can't hand a seat to. `open` names the ones this worker opens and hosts.
|
|
37
38
|
*/
|
|
38
39
|
| { readonly kind: 'place'; readonly id: number; readonly cells: readonly PlacedCell[]; readonly open: readonly string[] }
|
|
40
|
+
/**
|
|
41
|
+
* GC15 (3): a seat on this worker's road (`from`) walks into `to`, a cell on another worker. The road sends the client `travel`, lets the
|
|
42
|
+
* seat go and says `out` on its port with the walker's motion; the door then points the socket at `to`'s worker (`arrive`).
|
|
43
|
+
*/
|
|
44
|
+
| { readonly kind: 'handOut'; readonly from: string; readonly device: string; readonly to: string }
|
|
45
|
+
/** GC15 (3): the seat `handOut` let go on another worker arrives in `to` at `at`: the room hears its `hello` again on the moved socket. */
|
|
46
|
+
| ({ readonly kind: 'arrive'; readonly from: string; readonly to: string; readonly at: ResumeAt; readonly port: MessagePort; readonly hello: ArrayBuffer; readonly motion: MotionSnapshot | null } & SeatEntry)
|
|
47
|
+
/** GC15 (3): cells on other workers a walker can stand in at their entryways: this worker's road drops its walls round them and crosses into them. */
|
|
48
|
+
| { readonly kind: 'open'; readonly cells: readonly string[] }
|
|
39
49
|
| { readonly kind: 'close' };
|
|
40
50
|
/** One 10 s reading of a worker (E7.8). */
|
|
41
51
|
export interface WorkerReading {
|
|
@@ -43,6 +53,11 @@ export interface WorkerReading {
|
|
|
43
53
|
readonly players: number; readonly held: number; readonly ticks: number; readonly ticksPerSecond: number;
|
|
44
54
|
readonly p50: number; readonly p95: number; readonly p99: number; readonly max: number; readonly drops: number;
|
|
45
55
|
readonly rss: number; readonly heap: number; readonly refused: number; readonly dropped: number; readonly frameBytes: number; readonly eventBytes: number;
|
|
56
|
+
/** SERVER-CELLS SC1: this worker thread's own memory beyond its heap, and its event-loop lag in ms (`loopLag`), when it measures them. */
|
|
57
|
+
readonly external?: number; readonly arrayBuffers?: number;
|
|
58
|
+
readonly lag?: { readonly p50: number; readonly p99: number; readonly max: number };
|
|
59
|
+
/** SERVER-CELLS SC8: each cell that ticked in this reading, its mean ms per tick (its awake cost; `workerTable`'s weights come from these). */
|
|
60
|
+
readonly cellMs?: Readonly<Record<string, number>>;
|
|
46
61
|
}
|
|
47
62
|
/** What a cell tells the worker it runs on. */
|
|
48
63
|
export type RoomNews =
|
|
@@ -60,7 +75,9 @@ export type RoomNews =
|
|
|
60
75
|
export interface WorkerResident { readonly cells: number; readonly road: boolean; readonly strips: number }
|
|
61
76
|
/** What a worker says to the door. */
|
|
62
77
|
export type WorkerNews =
|
|
63
|
-
| { readonly kind: 'booted'; readonly ms: number; readonly resident?: WorkerResident }
|
|
78
|
+
| { readonly kind: 'booted'; readonly ms: number; readonly resident?: WorkerResident; /** GC15 (3): its grid cells whose entryways stand (GC30), for the other workers' roads. */ readonly stands?: readonly string[] }
|
|
79
|
+
/** GC15 (3): a `handOut` that let nothing go (the seat had no live link, or was gone): the crossing is off and the seat stays where it was. */
|
|
80
|
+
| { readonly kind: 'handedOut'; readonly device: string; readonly from: string; readonly out: boolean }
|
|
64
81
|
| { readonly kind: 'failed'; readonly reason: string }
|
|
65
82
|
| { readonly kind: 'found'; readonly id: number; readonly held: boolean; readonly spawn: ResumeAt }
|
|
66
83
|
| { readonly kind: 'report'; readonly slug: string; readonly report: ChatReport }
|
|
@@ -10,7 +10,8 @@ import { parentPort, workerData } from 'node:worker_threads';
|
|
|
10
10
|
import { loadRapier } from '@wildshard/engine/physics/rapier';
|
|
11
11
|
import { readPackGrid, readPackProduct, type PackReads } from './packReader';
|
|
12
12
|
import { runCells, type CellPort } from './cellHost';
|
|
13
|
-
import { placeCell, type PlacedCell } from './gridCells';
|
|
13
|
+
import { placeCell, placedHash, type PlacedCell } from './gridCells';
|
|
14
|
+
import { loopLag } from './loopLag';
|
|
14
15
|
|
|
15
16
|
/** What the door boots a worker with. */
|
|
16
17
|
export interface CellWorkerData { readonly slugs: readonly string[]; readonly build: string; readonly origin: string; readonly cache: string; readonly holdMs?: number;readonly playtest?:boolean;
|
|
@@ -19,21 +20,23 @@ export interface CellWorkerData { readonly slugs: readonly string[]; readonly bu
|
|
|
19
20
|
/** GC15: `WORLD_CROSSING=worker`, this worker hosts the road between its cells. */
|
|
20
21
|
readonly crossing?: boolean;
|
|
21
22
|
/** SA33: the cells the door had placed when it booted this worker; a worker's module state is its own. */
|
|
22
|
-
readonly placed?: readonly PlacedCell[]
|
|
23
|
+
readonly placed?: readonly PlacedCell[];
|
|
24
|
+
/** SERVER-CELLS SC1: `METRICS_PORT` is set, so this worker measures its event-loop lag for `/metrics`. */
|
|
25
|
+
readonly metrics?: boolean }
|
|
23
26
|
|
|
24
|
-
const { slugs, build, origin, cache, holdMs, emptyMs, playtest, crossing, placed } = workerData as CellWorkerData, port = parentPort;
|
|
27
|
+
const { slugs, build, origin, cache, holdMs, emptyMs, playtest, crossing, placed, metrics } = workerData as CellWorkerData, port = parentPort;
|
|
25
28
|
if (port === null) throw new Error('A cell runs in a worker');
|
|
26
29
|
for (const row of placed ?? []) placeCell(row);
|
|
27
30
|
const reads: PackReads = { fetched: 0, fetchedBytes: 0, cached: 0, refused: 0 };
|
|
28
31
|
const rapier = await loadRapier(await readFile(new URL('rapier.wasm', import.meta.url)));
|
|
29
|
-
runCells(port as unknown as CellPort, { slugs, build, bootId: () => randomBytes(4).toString('hex'), memory: () => process.memoryUsage(), closed: () => { process.exit(0); }, ...(holdMs === undefined ? {} : { holdMs }), ...(emptyMs === undefined ? {} : { emptyMs }),...(playtest===undefined?{}:{playtest}),...(crossing === true ? { road: async () => {
|
|
32
|
+
runCells(port as unknown as CellPort, { slugs, build, bootId: () => randomBytes(4).toString('hex'), memory: () => process.memoryUsage(), ...(metrics === true ? { lag: loopLag() } : {}), closed: () => { process.exit(0); }, ...(holdMs === undefined ? {} : { holdMs }), ...(emptyMs === undefined ? {} : { emptyMs }),...(playtest===undefined?{}:{playtest}),...(crossing === true ? { road: async () => {
|
|
30
33
|
// A build whose server book has no grid pack gives a road with no strips: this line says so before anyone falls through it.
|
|
31
34
|
const strips = await readPackGrid(build, { origin, cache }, reads);
|
|
32
35
|
console.info(JSON.stringify({ at: 'road.pack', strips: strips.length, ...reads }));
|
|
33
36
|
return strips;
|
|
34
37
|
} } : {}),
|
|
35
38
|
load: async slug => {
|
|
36
|
-
const input = await readPackProduct(slug, build, rapier, { origin, cache }, reads);
|
|
39
|
+
const input = await readPackProduct(slug, build, rapier, { origin, cache }, reads, placedHash(slug));
|
|
37
40
|
console.info(JSON.stringify({ at: 'cell.pack', slug, ...reads }));
|
|
38
41
|
return input;
|
|
39
42
|
} });
|
|
@@ -18,6 +18,7 @@ import type { FallFloor } from '../standalone/fallFloor';
|
|
|
18
18
|
import { ledgerFilings } from '../standalone/ledgerFilings';
|
|
19
19
|
import { questBooks } from '@wildshard/engine/quest/players';
|
|
20
20
|
import { mountedPlayerOf } from '@wildshard/engine/game/riding/native';
|
|
21
|
+
import { nativeTamingControls } from '@wildshard/engine/game/riding/nativeTaming';
|
|
21
22
|
import { carryDoc, exportPlayer, importPlayer, parseDoc, PLAYER_DOC_VERSION, type PlayerDoc } from './playerDoc';
|
|
22
23
|
import { PlayerStore, recoverPlayer } from './playerStore';
|
|
23
24
|
import { ShopGate } from './shopGate';
|
|
@@ -44,6 +45,8 @@ const DEBOUNCE_MS = 1000, EVERY_MS = 60_000;
|
|
|
44
45
|
/** A player who holds a seat, with or without a live link. */
|
|
45
46
|
interface Seat {
|
|
46
47
|
readonly device: string; readonly name: string; readonly body: string; readonly store: PlayerStore; readonly fall: FallFloor;
|
|
48
|
+
/** SC10: this device's own body id (`entry.body`), which `body` is unless it holds the lead seat: what it was paid here is kept under it. */
|
|
49
|
+
readonly own: string;
|
|
47
50
|
transport: Transport | null;
|
|
48
51
|
/** The link's client in this room's `NetRoom`, and how to stop hearing its close, while it stands. */
|
|
49
52
|
client: number | null; closeOff: (() => void) | null;
|
|
@@ -88,6 +91,9 @@ export interface DedicatedRoomOptions {
|
|
|
88
91
|
|
|
89
92
|
/** How `loot/personal` marks what a player has been paid. */
|
|
90
93
|
const LOOT_ROW = 'loot:';
|
|
94
|
+
/** 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
|
|
95
|
+
* 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. */
|
|
96
|
+
export const FORGET_PAID_MS = 300_000;
|
|
91
97
|
/** 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
98
|
const portableEntity = (entity: string, body: string): string => entity === body ? 'player' : entity.startsWith(`${body}:`) ? entity.slice(body.length + 1) : entity;
|
|
93
99
|
|
|
@@ -179,6 +185,8 @@ export class DedicatedRoom implements CrossTarget {
|
|
|
179
185
|
/** The lead's body leaves the world, and its seat stays for the systems bound to it. `removePlayer` refuses it. */
|
|
180
186
|
/** Seats taken since this world began. */
|
|
181
187
|
private joined = 0;
|
|
188
|
+
/** SC10: bodies that left, and when: what they were paid here is forgotten `FORGET_PAID_MS` on. */
|
|
189
|
+
private readonly departed = new Map<string, number>();
|
|
182
190
|
/** 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
191
|
private readonly arriving = new Set<string>();
|
|
184
192
|
private parkLead(): void { const { lead } = this; lead.motor.setEnabled(false); this.host.parked.add(lead.id); }
|
|
@@ -211,9 +219,11 @@ export class DedicatedRoom implements CrossTarget {
|
|
|
211
219
|
} }
|
|
212
220
|
catch (error) { return `recovery: ${String(error)}`; }
|
|
213
221
|
const store = new PlayerStore(doc?.store ?? {}, () => { const own = this.seats.get(entry.device); if (own !== undefined) this.dirty(own); });
|
|
214
|
-
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);
|
|
216
|
-
|
|
222
|
+
const seat: Seat = { device: entry.device, name: entry.name, read: entry.doc, body, own: entry.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 };
|
|
223
|
+
this.seats.set(entry.device, seat); this.bodies.set(body, seat); this.departed.delete(body);
|
|
224
|
+
// SC10 review: the lead seat takes back what this device was paid here when it last left (kept under its own id)
|
|
225
|
+
const away = this.departed.get(entry.body);
|
|
226
|
+
if (lead) { this.departed.delete(entry.body); this.movePaid(entry.body, LEAD_SEAT); this.unparkLead(); }
|
|
217
227
|
// Two who join together would otherwise stand inside each other.
|
|
218
228
|
const aside = SPAWN_ASIDE[(this.joined++) % SPAWN_ASIDE.length] ?? 0, stand = { ...spawn, x: spawn.x + aside };
|
|
219
229
|
const player = lead ? this.lead : host.addPlayer(body, at ?? doc?.at ?? stand, at?.yaw ?? doc?.at.yaw ?? spawn.yaw);
|
|
@@ -224,8 +234,9 @@ export class DedicatedRoom implements CrossTarget {
|
|
|
224
234
|
try { this.cell.owned.of(body); if (doc !== null) importPlayer(this.host, player, doc); if (at !== undefined) player.resetPose(at, at.yaw); }
|
|
225
235
|
catch (error) {
|
|
226
236
|
// 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.
|
|
228
|
-
|
|
237
|
+
this.seats.delete(entry.device); this.bodies.delete(body); this.cell.owned.drop(body); book.drop(body);
|
|
238
|
+
// review MUST: a failed continuation keeps what this device was paid here, on the clock it left on
|
|
239
|
+
if (lead) this.clearLead(entry.body, away ?? now); else host.removePlayer(body);
|
|
229
240
|
return `doc: ${String(error)}`;
|
|
230
241
|
}
|
|
231
242
|
return seat;
|
|
@@ -333,8 +344,8 @@ export class DedicatedRoom implements CrossTarget {
|
|
|
333
344
|
private release(seat: Seat): void {
|
|
334
345
|
this.playerRefusals.delete(seat.body);
|
|
335
346
|
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.
|
|
337
|
-
if (seat.body === LEAD_SEAT) this.clearLead(); else this.host.removePlayer(seat.body);
|
|
347
|
+
this.seats.delete(seat.device); this.bodies.delete(seat.body); this.cell.owned.drop(seat.body); this.book.drop(seat.body);
|
|
348
|
+
if (seat.body === LEAD_SEAT) this.clearLead(seat.own, this.options.now()); else { this.host.removePlayer(seat.body); this.departed.set(seat.body, this.options.now()); }
|
|
338
349
|
this.options.post({ kind: 'left', device: seat.device, seats: this.seats.size });
|
|
339
350
|
}
|
|
340
351
|
private flushRefusals(): void {
|
|
@@ -348,13 +359,28 @@ export class DedicatedRoom implements CrossTarget {
|
|
|
348
359
|
transport?.close('refused');
|
|
349
360
|
}
|
|
350
361
|
}
|
|
351
|
-
/**
|
|
352
|
-
|
|
362
|
+
/**
|
|
363
|
+
* 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).
|
|
364
|
+
* SC10 review: it goes under the leaver's own id, as any other body's stays, so a lead who bounces across an edge cannot re-farm a
|
|
365
|
+
* bounty; it is forgotten `FORGET_PAID_MS` after `left`. The seat's taming session goes too: the next lead starts wild.
|
|
366
|
+
*/
|
|
367
|
+
private clearLead(own: string, left: number): void {
|
|
353
368
|
actRoutes(this.host).identities.delete(LEAD_SEAT);
|
|
354
|
-
|
|
355
|
-
|
|
369
|
+
this.movePaid(LEAD_SEAT, own);
|
|
370
|
+
this.departed.set(own, left);
|
|
371
|
+
nativeTamingControls(this.host)?.release(LEAD_SEAT);
|
|
356
372
|
importPlayer(this.host, this.lead, this.blank); this.parkLead();
|
|
357
373
|
}
|
|
374
|
+
/** What `from` was paid here is `to`'s now. */
|
|
375
|
+
private movePaid(from: string, to: string): void {
|
|
376
|
+
const { ledgerDedupe } = this.host.slots, paid = `${LOOT_ROW}${from}:`;
|
|
377
|
+
for (let index = 0; index < ledgerDedupe.length; index++) { const row = ledgerDedupe[index]; if (row?.startsWith(paid) === true) ledgerDedupe[index] = `${LOOT_ROW}${to}:${row.slice(paid.length)}`; }
|
|
378
|
+
}
|
|
379
|
+
/** 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). */
|
|
380
|
+
private forgetPaid(body: string): void {
|
|
381
|
+
const { ledgerDedupe } = this.host.slots, paid = `${LOOT_ROW}${body}:`;
|
|
382
|
+
ledgerDedupe.splice(0, ledgerDedupe.length, ...ledgerDedupe.filter(row => !row.startsWith(paid)));
|
|
383
|
+
}
|
|
358
384
|
private step(inputs: readonly NetTickInput[]): void {
|
|
359
385
|
const { host, cell } = this, routes = actRoutes(host);
|
|
360
386
|
const accepted = inputs.map(input => ({ ...input, acts: input.acts.filter(act => { if (act.kind !== 'climate') return true; routes.refused++; return false; }) }));
|
|
@@ -423,6 +449,7 @@ export class DedicatedRoom implements CrossTarget {
|
|
|
423
449
|
if (stand !== seat.stand || version !== seat.version) { seat.stand = stand; seat.version = version; this.dirty(seat); }
|
|
424
450
|
if ((seat.dirtyAt !== null && now - seat.dirtyAt >= DEBOUNCE_MS) || now - seat.savedAt >= EVERY_MS) this.write(seat, 'checkpoint');
|
|
425
451
|
}
|
|
452
|
+
for (const [body, left] of this.departed) if (now - left >= FORGET_PAID_MS) { this.departed.delete(body); this.forgetPaid(body); }
|
|
426
453
|
}
|
|
427
454
|
/** Everyone goes, as at SIGTERM: their last checkpoint now, and a close that says a restart is why. */
|
|
428
455
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
}
|