Files
shacraft-core/docs/SERVER.md
T

81 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# MVP server, protocol, and operation
## Running the server
Rust 1.96+ and a modern browser with WebGL2 are required. Java is not needed to run Shacraft: the verified catalog is included in the source tree. Node 22+ is used for client and network checks.
```sh
cargo build --release --locked --workspace
bash scripts/run.sh --data data --listen 127.0.0.1:4000
```
Open http://127.0.0.1:4000. To let friends connect over a local network, use `--listen 0.0.0.0:4000`; browser SHA-256 verification requires HTTPS for addresses other than localhost. External access requires a standard HTTPS/WSS reverse proxy. The MVP has no account service; a player name is not an authenticated identity. Only the server owner receives the control token; it is never sent to the client.
`--data` selects the WorldStore directory; `--cache-sections` sets the shared cache capacity (64 by default). `--client` and `--packages` specify the static client and verified package directories. The startup script explicitly resolves these paths relative to the extracted project. Stop the server with Ctrl+C; already acknowledged edits do not depend on a clean process shutdown.
The first launch creates a lobby, the `gallery` world, an immutable Spleef base, and two independent arenas. The catalog contains every Java 26.2 block state and an original trampoline. The server can also open an imported WorldStore; imported worlds appear in the world selector alongside the demo worlds. The gallery contains 1,197 default-state samples on a 128×128 floor, spaced 3 blocks apart. It provides an overview of all block types, rather than all 32 thousand state variants. The gallery spawn is `[-50,2,58]`; the client loads the world in parts as the player moves.
## State ownership
One dedicated thread owns WorldStore, physics, and game state. HTTP and WebSocket handlers enqueue bounded commands. Movement runs at 20 ticks per second: speed is 5 blocks/s, gravity is 20 blocks/s², and the normal jump impulse is 7 blocks/s. The player's AABB is 0.6×1.8 blocks; the position specifies the center of their feet. +Y points up, yaw increases to the right, and pitch increases upward; the viewing direction is `[sin(yaw)*cos(pitch),sin(pitch),-cos(yaw)*cos(pitch)]`.
Gameplay positions and spawn points are limited to ±32,700 on each axis because this client's physics uses `f32`. Storage and the converter retain their wider ±30,000,000 contract; this does not guarantee gameplay physics at distant coordinates. A player who leaves the gameplay range returns to spawn, or is eliminated during an active match.
Input expresses movement intent rather than position. The server checks the 6-block reach, the nearest shape intersection, the placement cell, intersections with players, and arena rules. Stale input is cleared after one second. Gameplay physics reads a bounded region of neighboring blocks for each tick; independent worlds without players need no array of loaded sections.
`worlds.sqlite3` stores blocks and their history. `server.sqlite3` stores configuration and persistent entities, with a separate revision. These are two transaction domains: creating a world and adding its settings are not claimed to form one shared transaction. If saving settings fails after world creation, the world remains available with safe defaults; the error must not be interpreted as permission to create the same world again. A failed entity or settings write restores state from the last saved version. If even reading SQLite fails, the operation returns an error; a storage failure is never acknowledged as success.
## HTTP and authorization
Public GET endpoints: `/api/health`, `/api/manifest`, `/api/worlds`, `/api/catalog`, `/api/entities`, `/api/metrics`. The catalog accepts `query`, `offset`, `limit` (1–256), `ids` with at most 128 runtime IDs, or `states` containing canonical states separated by commas outside property brackets. Obtain runtime IDs from the response; they do not match Minecraft's numeric IDs.
`POST /api/control` accepts `{ "method": "world.read", "params": {...} }` and returns `{ "result": ... }`, or HTTP 400 with `{ "error": "..." }`. It requires `Authorization: Bearer <token>`. On the first launch, `control.token` is created with Unix mode 0600. Operation parameters are available in the separate MCP server's `tools/list` schemas. Control API names use a dot: `world.edit`, `build.plan`, `camera.capture`, and so on.
The token is not secret from the local machine's administrator. The manifest hash confirms resource compatibility; it does not prove that the client's executable code is unmodified. Game state protection relies on server-side validation. Browser WebSocket and Control API requests are subject to Origin checks; cross-site access is not enabled.
## WebSocket, snapshots, and edits
Send the first message to `/ws` within 10 seconds:
```json
{"type":"join","protocol":1,"manifest_hash":"from /api/manifest","name":"Player","world":"lobby"}
```
`welcome` contains `id`, `world`, `revision`, `blocks:[{pos,block}]`, definitions of the `materials` in use, `players`, `entities`, `spawn`, `view_center`, and `manifest_hash`. A snapshot covers `[centerX-32, centerY-8, centerZ-32]…[centerX+31, centerY+31, centerZ+31]`, with inclusive upper bounds. When the view center moves, the server sends a new `snapshot`; the client replaces its geometry completely. Snapshots do not include the full string registry. `materials` is limited to 256 entries and 128 KiB; the client requests the remaining definitions sequentially through `/api/catalog?ids=1,2,...&limit=128`. This allows players to join worlds with large palettes without overflowing the outbound queue.
The client sends `input` with `seq,yaw,pitch,forward,strafe,jump`; `break` with `pos`; `place` with `pos,block` or `state`; and `switch_world`, `resync`, `respawn`, `start_match`, `chat`, and `ping`. A `state` response contains authoritative positions, `tick`, the acknowledged input `ack`, and match state. Blocks arrive in `blocks` messages with a new revision. If a revision is missing, the client requests a snapshot. Subscription and snapshot creation are serialized with edits on the same thread, so an edit made between those steps cannot be lost.
Control edits retain the core contract: an expected revision, a unique `operation_id`, a durable acknowledgment, replay of the same request without a second write, and rejection on conflict. A build plan covers at most 32,768 cells and is retained for 5 minutes, with at most 16 plans stored; preview does not change the world. Plans are ephemeral and disappear after a restart; accepted edits remain on disk. `camera.capture` returns a PNG of the server's isometric projection and the exact revision; it is not a frame from the player's WebGL camera.
## Spleef rules
A match follows `waiting → countdown → active → finished → waiting`. Defaults are 2 required players, a 3-second countdown, and a round lasting up to 180 seconds. Only `minecraft:snow_block` may be broken during an active round; block placement and boundary destruction are forbidden. Falling below Y=−6 eliminates a player. The last remaining participant wins; if time expires with multiple participants remaining, the result is a draw. Five seconds after the result, the world returns to its pinned template and players return to spawn. Arenas are independent. Disconnecting or leaving the world removes a participant; rejoining during the round admits them as a spectator. After a restart, an interrupted match resets to its template.
`arena.configure` persists world settings. They can be changed between matches; attempts during countdown/active/finished are rejected. Available fields are `mode`, `spawn`, and:
- `countdown_seconds`: integer 1…30, default 3; `round_seconds`: integer 1…3600, default 180.
- `min_players`: integer 2…32, default 2.
- `elimination_y`: a finite coordinate within ±32,700, default −6.
- `spawn_points`: up to 32 `[x,y,z]` points. An empty list uses a circle of radius 7 around X/Z=0 at height `spawn[1]`. A nonempty list must accommodate the minimum player count and, at match start, every player who has joined; points must be at least 0.8 blocks apart.
- `spectator_spawn`: spectator position, default `[13,2,0]`.
- `floor_block`: a known canonical state with collision that participants are allowed to break. Default: `minecraft:snow_block`. The pinned map's floor must already contain this material; configure does not repaint or rebuild the map.
All spawn points must be within the gameplay range, with Y above `elimination_y + 0.5`. The optional `expected_revision` checks the shared metadata revision available through `entity.list`/`metrics`; this is separate from world block revisions. Rules are returned in `match.rules`. Older settings containing only `mode/spawn` are read using the defaults above.
The core idempotency journal covers block edits, undo/reset, and build commits. Entity operations and arena configuration do not yet have such a journal: repeating `entity.spawn` creates another instance. After an uncertain network result, read the current state first.
## Limits and observability
- 32 WebSocket sessions, including those waiting to join; 16 concurrently served HTTP requests; a 64-command queue.
- WebSocket input messages up to 64 KiB, with at most 80 messages/s per connection; block actions no more often than every 110 ms, chat every 700 ms, explicit resync every 500 ms, world switches every second, and automatic snapshots on section changes every 2 seconds.
- Control API JSON up to 2 MiB; standard edits up to 32,768 cells; reads up to 262,144 cells and 6 MiB of response data. Exceeding the byte limit requires a smaller region.
- Each client's outbound queue holds up to 16 messages and 8 MiB. A slow connection is closed if its queue overflows or sending times out. The aggregate queue bound depends on the number of clients; these bytes are separate from the section cache.
- Server metadata up to 8 MiB, at most 4096 entities, and up to 16 KiB of properties per entity. Gameplay snapshots contain compact representations without arbitrary property JSON; full properties are available through `entity.list` with offset and limit (default 64, maximum 128).
- Process RAM in `/api/metrics` is the actual Linux VmRSS; `storage.cache_payload_bytes` counts only the payload bytes of encoded sections. The catalog, strings, SQLite, network buffers, temporary reads, and allocator memory are separate allocations.
The maximum allowed configuration is not the measured target load profile. Benchmark conditions and results are published in VERIFICATION; no advantage over Paper is claimed without a comparable run.
## Entities and compatibility
The 158 entity definitions have measured dimensions and original procedural models. Persistent instances can be created, moved, and deleted through MCP. Full vanilla AI, redstone, fluids, inventories, and Minecraft gameplay logic are not implemented. Context-dependent block shapes are explicitly marked in the catalog. The converter handles modified and unknown data according to `docs/interop.md`, without silently claiming lossless compatibility.