Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docker/compose.watch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
#
# Unprivileged: read-only root, no capabilities, 1 CPU at the lowest share, only the iGPU render node, world directories
# read-only. Renders only below --max-load, at most --max-megas mega tiles per batch, closest to a player first.
#
# To receive block-change events from the game server (TORO-Core's map-dirty module) as well, add
# "--dirty-port", "9109" and "--dirty-token-file", "/run/secrets/dirty_token" to the command, publish the port on
# the network the game server can reach (a network both stacks share, not the host's public interface), and add
# the token as another secret. Without a token the feed stays off.
services:
watch:
image: ghcr.io/toro-server/toro-renderer:latest
Expand Down
12 changes: 12 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
| `scripts/job/watch_job.gd` | 複数マップの常駐更新 |
| `scripts/job/gate.gd` | 描画してよいかの判定(負荷、プレイヤーの有無) |
| `scripts/job/live_feed.gd` | プレイヤー位置の WebSocket 購読 |
| `scripts/job/dirty_feed.gd` | ゲームサーバーからのブロック変更イベント(WebSocket サーバー、token 認証) |

## 設計上の判断

Expand Down Expand Up @@ -67,3 +68,14 @@ MySQL クライアントが無いための自作で、データベースは同
**プレイヤー位置で優先順位を付ける。** 描画の待ち行列を、メガタイルからプレイヤーまでの距離(マップ自身の投影を通した
メガタイル単位)で並べる。長く待っているものは先頭へ出す。位置は Dynmap のマップが表示するプレイヤーのものなので、
非表示のプレイヤーは含まれない。

**変更検出はイベントと Anvil の二層。** ゲームサーバー(TORO-Core の map-dirty モジュール)がブロック変更を
チャンク単位で集めて WebSocket で送り、watch はそれを Anvil の検出と同じ待ち行列に合流させる(先に入った時刻を保持)。
イベントは検知を速くするだけで、取りこぼしても Anvil の周期スキャンが拾う。逆にイベントだけに頼らないので、
サーバー側の連携が止まっても地図は止まらない。token は接続直後の 1 通で見せる(Godot の WebSocket サーバーは
接続時のヘッダーを読めないため、dynmap-live のヘッダー方式は取れない)。

**洪水制御は描画側に置く。** WorldEdit の一括編集や高速設置の荒らしは、検知側では量を潰しきれない(範囲が正当な
変更と区別できない)。そこで watch の待ち行列で、再描画の間隔(`--mega-cooldown`)、繰り返し変わるメガタイルの
降格と 1 バッチの枠上限、最古参の予約枠、滞留時の行順処理(`--bbox-threshold`)を効かせる。描画の予算
(Gate、1 バッチの数、転送速度)は変えない。対象は捨てず、待つ時間が延びるだけにする。
8 changes: 8 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,16 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [--
| `--overlap S` | 30 | 次の周期が少し前から始まるための重なり(取りこぼし防止) |
| `--max-megas N` | 4 | 1 バッチのメガタイル数 |
| `--stale-after-queue S` | 600 | この秒数より長く待った分を最優先にする |
| `--mega-cooldown S` | 240 | 描いたメガタイルを再び描けるようになるまでの秒数(洪水制御。0 で無効) |
| `--bbox-threshold N` | 256 | 待ち行列がこの数以上になったマップは、優先順位ではなく範囲内の行順に処理する(0 で無効) |
| `--dirty-port N` | 0 | ゲームサーバー(TORO-Core の map-dirty)からのブロック変更イベントを受ける WebSocket のポート。0 で無効 |
| `--dirty-token-file F` | | イベントの token を読むファイル(環境変数 `TORO_DIRTY_TOKEN` が優先)。`--dirty-port` と token の両方がそろったときだけ受ける |
| `--once` | | 1 回見て、最大 1 バッチだけ処理して終了(試験用) |

イベントは待ち行列に合流し、すでに入っているメガタイルは最初に入った時刻のままになる。繰り返し変わるメガタイルは
「熱い」と数えて順位を下げ、1 バッチに入る数も半分(最低 1)までに抑える。どのバッチでも最古の 1 件は必ず席を得る。
どれも捨てる仕組みではなく、待つ時間が延びるだけである。

## `zoom`

`zoom --map-id N --zoom-max Z (--all | --seed FILE)`: 描かずに zoom-out を再構築する。`FILE` は 1 行に 1 タイル
Expand Down
21 changes: 21 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,27 @@ docker compose -f docker/compose.watch.yaml up -d
初回の起動時は、その時点以降の変更だけを見る(`since` は起動時刻から)。停止中に起きた変更も、領域ファイルの時刻から
拾える。

### ブロック変更イベント(WebSocket、任意)

`--dirty-port` と token(環境変数 `TORO_DIRTY_TOKEN` か `--dirty-token-file`)を指定すると、ゲームサーバーの
TORO-Core(map-dirty モジュール)からの接続を受ける。ゲームサーバーはブロック変更をチャンク単位で集め、
デバウンス窓(既定 10 秒)ごとに送ってくる。受けたチャンクは Anvil の検出と同じ待ち行列に合流し、
すでに入っているメガタイルは最初に入った時刻のままになる。

- 送る側の最初の 1 通: `{"t":"auth","token":"..."}`(Godot の WebSocket サーバーは接続時のヘッダーを読めないので、
token はヘッダーではなくこの形で見せる。認証前に来た変更は捨て、token が違えば切る)
- 続く 1 通ごと: `{"t":"dirty","worlds":{"<ワールド>":{"bukkit":[[cx,cz],...],"worldedit":[...]}}}`

イベントは検知を速くするだけのもので、止まっても Anvil の周期スキャンが拾うので地図は止まらない。
ポートはホストの外向けではなく、ゲームサーバーと watch が共有する Docker ネットワークの中だけで届くようにする。

洪水制御も待ち行列側で効く。描いたメガタイルは `--mega-cooldown`(既定 240 秒)の間は描き直さない
(`--stale-after-queue` を超えて待ったものは除く)。待ち行列にいる間に何度も変更が来たメガタイルは「熱い」と数え、
順位を下げ、1 バッチに入る数を半分(最低 1)までに抑える。どのバッチにも最古の 1 件の席は確保する。
待ち行列が `--bbox-threshold`(既定 256)以上になったマップは、優先順位をやめて範囲内の行順に処理する。
どれも対象を捨てる仕組みではなく、待つ時間が延びるだけである。クールダウンと熱さは状態ファイルに保存され、
再起動しても残る。

### プレイヤー位置(WebSocket)

設定に `live` があると、[`LiveFeed`](../scripts/job/live_feed.gd) が監視する各 Dynmap ワールドをマップサイトの `/up/ws` へ
Expand Down
19 changes: 18 additions & 1 deletion scripts/cmd/jobs.gd
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ static func run(args: Args) -> int:


## `watch --config maps.json [--map-id N,...] [--interval S] [--max-megas N] [--max-load L] [--stale-after S] [--once]`
## Resident updater for every map of the config.
## [--mega-cooldown S] [--bbox-threshold N] [--dirty-port N] [--dirty-token-file F]`
## Resident updater for every map of the config. The dirty feed (block-change events from the game server)
## listens only when both a port and a token are set: the token comes from TORO_DIRTY_TOKEN or the file.
static func watch(args: Args) -> int:
var ctx := Context.create(args, 2.5, -1)
if ctx.cfg.get("maps", []).is_empty():
Expand All @@ -63,7 +65,22 @@ static func watch(args: Args) -> int:
job.overlap = args.number("overlap", 30.0)
job.max_megas = args.integer("max-megas", 4)
job.stale_after = args.number("stale-after-queue", 600.0)
job.mega_cooldown = args.number("mega-cooldown", 240.0)
job.bbox_threshold = args.integer("bbox-threshold", 256)
job.once = args.flag("once")
var dirty_port := args.integer("dirty-port", 0)
if dirty_port > 0:
var token := OS.get_environment("TORO_DIRTY_TOKEN")
if token == "" and args.has("dirty-token-file"):
var tf := FileAccess.open(args.text("dirty-token-file"), FileAccess.READ)
if tf != null:
token = tf.get_as_text().strip_edges()
if token == "":
Term.say("warning: --dirty-port without a token (TORO_DIRTY_TOKEN or --dirty-token-file): the dirty feed stays off")
else:
var dirty := DirtyFeed.new()
if dirty.start(dirty_port, token):
job.dirty_feed = dirty
var state_dir := args.text("state-dir", "/state")
for e in ctx.cfg["maps"]:
var map := MapDef.from_entry(e)
Expand Down
164 changes: 164 additions & 0 deletions scripts/job/dirty_feed.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
class_name DirtyFeed
extends RefCounted
## Receives block-change events from the game server (TORO-Core's map-dirty module) over one WebSocket.
## The game server connects here and shows the shared token in a first {"t":"auth","token":...} message --
## Godot's WebSocket server cannot read the handshake headers, so the token cannot travel in one the way
## dynmap-live sends it to the map site; the style (one socket, one shared token, reconnect with backoff on
## the sender side) is the same. Until a connection is authenticated its messages are dropped.
##
## After that the server sends {"t":"dirty","worlds":{"<world>":{"bukkit":[[cx,cz],...],"worldedit":[...]}}}
## once per debounce window. Chunks wait here, per world, until the watch drains them into its pending queue;
## nothing is rendered from this class.

const MAX_CLIENTS := 8
const MAX_WORLDS := 64
const MAX_CHUNKS_PER_MESSAGE := 1_000_000
const AUTH_MSEC := 10_000

var _server := TCPServer.new()
var _token := ""
var _clients: Array = [] # {peer: WebSocketPeer, authed: bool, deadline: int (ticks msec)}
var _queue := {} # world -> {Vector2i: true}
var _connected := false


## Starts listening. Returns false (and never listens) without a token or when the port is taken.
func start(port: int, token: String) -> bool:
if port <= 0 or token == "":
return false
if _server.listen(port) != OK:
push_warning("dirty feed: cannot listen on port %d" % port)
return false
_token = token
_connected = true
(Engine.get_main_loop() as SceneTree).process_frame.connect(poll)
Term.say("dirty feed listening on port %d" % port)
return true


func stop() -> void:
if _connected:
(Engine.get_main_loop() as SceneTree).process_frame.disconnect(poll)
_connected = false
for c in _clients:
(c["peer"] as WebSocketPeer).close()
_clients.clear()
_server.stop()


## Accepts connections and reads messages. Runs every frame of the main loop while started.
func poll() -> void:
while _server.is_connection_available() and _clients.size() < MAX_CLIENTS:
var peer := WebSocketPeer.new()
if peer.accept_stream(_server.take_connection()) != OK:
continue
_clients.append({"peer": peer, "authed": false, "deadline": Time.get_ticks_msec() + AUTH_MSEC})
var now := Time.get_ticks_msec()
var alive: Array = []
for c in _clients:
var peer: WebSocketPeer = c["peer"]
peer.poll()
match peer.get_ready_state():
WebSocketPeer.STATE_OPEN:
while peer.get_available_packet_count() > 0:
_message(c, peer.get_packet().get_string_from_utf8())
alive.append(c)
WebSocketPeer.STATE_CONNECTING:
if not c["authed"] and now > int(c["deadline"]):
peer.close()
else:
alive.append(c)
WebSocketPeer.STATE_CLOSING:
alive.append(c)
_clients = alive


func _message(c: Dictionary, text: String) -> void:
var msg = JSON.parse_string(text)
if not (msg is Dictionary):
return
if not c["authed"]:
if msg.get("t") is String and msg["t"] == "auth" and msg.get("token") is String and msg["token"] == _token:
c["authed"] = true
else:
(c["peer"] as WebSocketPeer).close()
return
if msg.get("t") is String and msg["t"] == "dirty":
var parsed := parse_dirty(msg)
for world: String in parsed:
if not _queue.has(world):
_queue[world] = {}
var seen: Dictionary = _queue[world]
for chunk in parsed[world]:
seen[chunk] = true


## The chunks of one dirty message: world -> Array[Vector2i]. Bad entries are dropped, and a message is
## capped so a broken or hostile sender cannot grow the queue without bound.
static func parse_dirty(msg: Dictionary) -> Dictionary:
var out := {}
var worlds = msg.get("worlds")
if not (worlds is Dictionary):
return out
var total := 0
for world: String in worlds:
if out.size() >= MAX_WORLDS:
break
var by_source = worlds[world]
if not (by_source is Dictionary):
continue
var chunks: Array = []
var seen := {}
for source: String in by_source:
var list = by_source[source]
if not (list is Array):
continue
for e in list:
if not (e is Array) or e.size() != 2 or not _coord(e[0]) or not _coord(e[1]):
continue
var chunk := Vector2i(int(e[0]), int(e[1]))
if seen.has(chunk):
continue
seen[chunk] = true
chunks.append(chunk)
total += 1
if total >= MAX_CHUNKS_PER_MESSAGE:
break
if total >= MAX_CHUNKS_PER_MESSAGE:
break
if not chunks.is_empty():
out[world] = chunks
if total >= MAX_CHUNKS_PER_MESSAGE:
break
return out


static func _coord(v: Variant) -> bool:
return v is int or (v is float and is_finite(v) and v == floorf(v))


## All received chunks so far: world -> Array[Vector2i]. Empties the queue.
func drain() -> Dictionary:
var out := {}
for world: String in _queue:
var chunks: Array = []
chunks.assign((_queue[world] as Dictionary).keys())
out[world] = chunks
_queue.clear()
return out


func queued() -> int:
var n := 0
for world: String in _queue:
n += (_queue[world] as Dictionary).size()
return n


## Connections that completed the token check.
func authenticated() -> int:
var n := 0
for c in _clients:
if c["authed"]:
n += 1
return n
1 change: 1 addition & 0 deletions scripts/job/dirty_feed.gd.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://bjmxr8o0kfavi
Loading
Loading