diff --git a/docker/compose.watch.yaml b/docker/compose.watch.yaml index b099cbc..91a7438 100644 --- a/docker/compose.watch.yaml +++ b/docker/compose.watch.yaml @@ -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 diff --git a/docs/architecture.md b/docs/architecture.md index 5ad7050..2690c7f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 認証) | ## 設計上の判断 @@ -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 バッチの数、転送速度)は変えない。対象は捨てず、待つ時間が延びるだけにする。 diff --git a/docs/commands.md b/docs/commands.md index 5c2c21c..7cfc179 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -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 タイル diff --git a/docs/operations.md b/docs/operations.md index c92f077..8539731 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -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` へ diff --git a/scripts/cmd/jobs.gd b/scripts/cmd/jobs.gd index 0baa2e3..d41c794 100644 --- a/scripts/cmd/jobs.gd +++ b/scripts/cmd/jobs.gd @@ -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(): @@ -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) diff --git a/scripts/job/dirty_feed.gd b/scripts/job/dirty_feed.gd new file mode 100644 index 0000000..feea80c --- /dev/null +++ b/scripts/job/dirty_feed.gd @@ -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":{"":{"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 diff --git a/scripts/job/dirty_feed.gd.uid b/scripts/job/dirty_feed.gd.uid new file mode 100644 index 0000000..6a09538 --- /dev/null +++ b/scripts/job/dirty_feed.gd.uid @@ -0,0 +1 @@ +uid://bjmxr8o0kfavi diff --git a/scripts/job/watch_job.gd b/scripts/job/watch_job.gd index 4014f2e..33a1fc6 100644 --- a/scripts/job/watch_job.gd +++ b/scripts/job/watch_job.gd @@ -8,11 +8,23 @@ extends RefCounted ## Order of work: mega tiles close to a player first (positions arrive over the WebSocket live feed), the rest in the order ## they were queued; anything waiting longer than --stale-after seconds goes ahead of everything else. ## +## Block-change events from the game server (DirtyFeed) merge into the same pending queue as the Anvil scan -- a mega +## tile that is already queued keeps its first queued time -- and flood control keeps a WorldEdit spree or a griefer +## placing blocks at full speed from starving the rest: a rendered mega waits out --mega-cooldown before it may be +## drawn again, a mega that keeps being re-offered while queued counts as hot (demoted, and only so many hot megas +## per batch), one seat of every batch is reserved for the oldest queued mega, and a map whose queue grows past +## --bbox-threshold is worked off in plain row order over its bounding box instead of by priority. Nothing is ever +## dropped for flooding: the worst case is a longer wait. +## ## A mega tile is counted as attempted (on disk) before drawing and the count is cleared afterwards, so a count that survives ## a restart means the process died on it. Those are retried one at a time and dropped after MAX_ATTEMPTS, so one bad chunk ## cannot keep the container in a crash loop. The tile is queued again the next time its chunks change. const MAX_ATTEMPTS := 3 +## A mega tile offered again at least this many times while queued counts as hot. +const HOT_HEAT := 3 +## Rank penalty per heat: one heat pushes a mega about this many mega tiles away from the players. +const HEAT_DISTANCE := 2.0 class MapState: var def: MapDef @@ -23,6 +35,10 @@ class MapState: var pending := {} ## Vector2i -> times the process started drawing it without finishing var attempts := {} + ## Vector2i -> unix time before which the mega tile may not be drawn again (flood control) + var cooldown_until := {} + ## Vector2i -> how often the mega tile was offered again while it was already queued (flood control) + var heat := {} var path := "" var maps: Array[MapState] = [] @@ -30,10 +46,16 @@ var pool: RendererPool var store: TileStore var gate: Gate var feed: LiveFeed +## Block-change events from the game server; null when the feed is off. +var dirty_feed: DirtyFeed var interval := 60.0 var overlap := 30.0 var max_megas := 4 var stale_after := 600.0 +## Seconds a rendered mega tile waits before events may have it drawn again (0 disables the cooldown). +var mega_cooldown := 240.0 +## A map with at least this many pending mega tiles is worked off in row order (0 disables). +var bbox_threshold := 256 ## true: one scan and at most one batch, then return (tests) var once := false var _zoom: ZoomBuilder @@ -58,6 +80,10 @@ func add(def: MapDef, state_dir: String) -> bool: ms.pending[m] = float(e[2]) if e.size() > 2 else Time.get_unix_time_from_system() if e.size() > 3 and int(e[3]) > 0: ms.attempts[m] = int(e[3]) + for e in st.get("cooldown", []): + ms.cooldown_until[Vector2i(int(e[0]), int(e[1]))] = float(e[2]) + for e in st.get("heat", []): + ms.heat[Vector2i(int(e[0]), int(e[1]))] = int(e[2]) maps.append(ms) return true @@ -67,11 +93,18 @@ func _save(ms: MapState) -> void: var pend := [] for m: Vector2i in ms.pending: pend.append([m.x, m.y, ms.pending[m], ms.attempts.get(m, 0)]) + var cool := [] + for m: Vector2i in ms.cooldown_until: + cool.append([m.x, m.y, ms.cooldown_until[m]]) + var heat := [] + for m: Vector2i in ms.heat: + if int(ms.heat[m]) > 0: + heat.append([m.x, m.y, ms.heat[m]]) var f := FileAccess.open(ms.path, FileAccess.WRITE) if f == null: push_warning("cannot write %s" % ms.path) return - f.store_string(JSON.stringify({"since": ms.since, "pending": pend})) + f.store_string(JSON.stringify({"since": ms.since, "pending": pend, "cooldown": cool, "heat": heat})) ## Forgets the mega tiles that already took the process down MAX_ATTEMPTS times. @@ -83,29 +116,140 @@ func _drop_failing(ms: MapState) -> void: ms.attempts.erase(m) -## The next batch from the queue in priority order. A tile the process died on goes alone, to tell which one is the cause. -func _next_group(ms: MapState, order: Array) -> Array[Vector2i]: +## True when the mega tile may be drawn now: not in its re-render cooldown, or already waiting so long that +## the cooldown no longer applies (an old tile is never held back forever). +func _eligible(ms: MapState, m: Vector2i, now: float) -> bool: + if now - float(ms.pending[m]) > stale_after: + return true + return float(ms.cooldown_until.get(m, 0.0)) <= now + + +func _is_hot(ms: MapState, m: Vector2i) -> bool: + return int(ms.heat.get(m, 0)) >= HOT_HEAT + + +## How many seats of one batch hot mega tiles may take: half of it, at least one, so a quiet map still drains. +func _hot_seats() -> int: + return maxi(1, max_megas / 2) + + +## The next batch from the queue. `order` is the pending mega tiles in priority order; mega tiles in their +## cooldown are skipped. A tile the process died on goes alone, to tell which one is the cause. Otherwise one +## seat is reserved for the oldest queued tile, and hot tiles are capped to _hot_seats() seats, so a spot that +## keeps changing cannot fill every batch while the rest of the map waits. +func _next_group(ms: MapState, order: Array, now := -1.0) -> Array[Vector2i]: + if now < 0.0: + now = Time.get_unix_time_from_system() + var ready: Array = [] + for m in order: + if _eligible(ms, m, now): + ready.append(m) var group: Array[Vector2i] = [] - group.assign(order.slice(0, max_megas)) - for m in group: + if ready.is_empty(): + return group + for m in ready: if ms.attempts.has(m): group.assign([m]) + return group + var oldest: Vector2i = ready[0] + for m in ready: + if float(ms.pending[m]) < float(ms.pending[oldest]): + oldest = m + group.append(oldest) + var hot_used := 1 if _is_hot(ms, oldest) else 0 + var deferred: Array = [] + for m in ready: + if group.size() >= max_megas: + break + if m == oldest: + continue + if _is_hot(ms, m): + if hot_used >= _hot_seats(): + deferred.append(m) + continue + hot_used += 1 + group.append(m) + for m in deferred: + if group.size() >= max_megas: break + group.append(m) return group +## The next batch in plain row order (north to south, then west to east) over everything queued, for a map +## whose queue outgrew priority sorting. Cooldowns and the alone-rule for failed tiles still apply; the tiles +## are not reordered by players or heat, so a batch covers one compact area. +func _next_group_bbox(ms: MapState, now: float) -> Array[Vector2i]: + var keys: Array = ms.pending.keys() + keys.sort_custom(func(a: Vector2i, b: Vector2i) -> bool: return a.y < b.y or (a.y == b.y and a.x < b.x)) + var group: Array[Vector2i] = [] + for m in keys: + if group.size() >= max_megas: + break + if not _eligible(ms, m, now): + continue + if ms.attempts.has(m): + group.assign([m]) + return group + group.append(m) + return group + + +## The pending bounding box as [min, max] mega tiles, for reporting the bbox mode. +func _pending_bbox(ms: MapState) -> Array: + var lo: Vector2i = ms.pending.keys()[0] + var hi := lo + for m: Vector2i in ms.pending: + lo = Vector2i(mini(lo.x, m.x), mini(lo.y, m.y)) + hi = Vector2i(maxi(hi.x, m.x), maxi(hi.y, m.y)) + return [lo, hi] + + +## Merges changed chunks into the pending queue. A mega tile that is already queued keeps the time it was +## first queued; when the chunks come from block-change events (count_heat), a mega tile that is offered again +## also gains heat, which the batch selection uses to demote it. Returns how many mega tiles were new. +func _offer(ms: MapState, chunks: Array[Vector2i], now: float, count_heat: bool) -> int: + if chunks.is_empty(): + return 0 + var fresh := AnvilChanges.megas_of(chunks, ms.persp, ms.def.min_y, ms.def.max_y, ms.def.mega) + var added := 0 + for m in fresh: + if ms.pending.has(m): + if count_heat: + ms.heat[m] = int(ms.heat.get(m, 0)) + 1 + else: + ms.pending[m] = now + added += 1 + return added + + func _scan(ms: MapState, now: float) -> void: var chunks := ms.changes.changed_since(ms.def.region_dir, ms.since) if not chunks.is_empty(): - var fresh := AnvilChanges.megas_of(chunks, ms.persp, ms.def.min_y, ms.def.max_y, ms.def.mega) - for m in fresh: - if not ms.pending.has(m): - ms.pending[m] = now - Term.say("map %d: %d changed chunks -> %d mega tiles (%d pending)" % [ms.def.id, chunks.size(), fresh.size(), ms.pending.size()]) + _offer(ms, chunks, now, false) + Term.say("map %d: %d changed chunks -> %d pending" % [ms.def.id, chunks.size(), ms.pending.size()]) # the next look starts a little earlier so nothing saved while this one was reading is missed ms.since = now - overlap +## Merges the block-change events the feed collected into the queues of their maps. +func _drain_dirty(now: float) -> void: + if dirty_feed == null: + return + var events: Dictionary = dirty_feed.drain() + for world: String in events: + var matched := false + for ms in maps: + if ms.def.world == world: + matched = true + var added := _offer(ms, events[world], now, true) + if added > 0: + Term.say("map %d: events queued %d new mega tiles (%d pending)" % [ms.def.id, added, ms.pending.size()]) + _save(ms) + if not matched: + Term.say("dirty events for unknown world '%s' dropped" % world) + + ## smaller = sooner func _rank(ms: MapState, m: Vector2i, queued: float, now: float) -> float: if now - queued > stale_after: @@ -116,7 +260,8 @@ func _rank(ms: MapState, m: Vector2i, queued: float, now: float) -> float: for p in feed.players(ms.def.world): var mp := ms.persp.world_to_map(float(p["x"]), float(p["y"]), float(p["z"])) best = minf(best, Vector2(m.x + 0.5 - mp[0] / side, m.y + 0.5 - mp[1] / side).length()) - return best + queued * 1e-10 + # a mega tile that keeps changing counts as farther away, so the rest of the map goes first + return best + queued * 1e-10 + float(int(ms.heat.get(m, 0))) * HEAT_DISTANCE ## Coroutine: `await watch.run()`. @@ -124,6 +269,7 @@ func run() -> int: Term.say("watching %d maps, cycle %.0f s" % [maps.size(), interval]) while true: var cycle := Time.get_unix_time_from_system() + _drain_dirty(cycle) for ms in maps: _scan(ms, cycle) _save(ms) @@ -157,6 +303,8 @@ func _work_one_group() -> bool: for ms in maps: _drop_failing(ms) for m: Vector2i in ms.pending: + if not _eligible(ms, m, now): + continue var r := _rank(ms, m, ms.pending[m], now) if r < best_rank: best_rank = r @@ -164,9 +312,17 @@ func _work_one_group() -> bool: if best_ms == null: return false var ms := best_ms - var order: Array = ms.pending.keys() - order.sort_custom(func(a: Vector2i, b: Vector2i) -> bool: return _rank(ms, a, ms.pending[a], now) < _rank(ms, b, ms.pending[b], now)) - var group := _next_group(ms, order) + var group: Array[Vector2i] + if bbox_threshold > 0 and ms.pending.size() >= bbox_threshold: + group = _next_group_bbox(ms, now) + var bb := _pending_bbox(ms) + Term.say("map %d: %d pending over the limit %d, working the bbox %s..%s in row order" % [ms.def.id, ms.pending.size(), bbox_threshold, bb[0], bb[1]]) + else: + var order: Array = ms.pending.keys() + order.sort_custom(func(a: Vector2i, b: Vector2i) -> bool: return _rank(ms, a, ms.pending[a], now) < _rank(ms, b, ms.pending[b], now)) + group = _next_group(ms, order, now) + if group.is_empty(): + return false if not store.ensure_connected(): Term.say("database unreachable: " + store.error) return false @@ -195,8 +351,12 @@ func _work_one_group() -> bool: store.error = "" _save(ms) return false + var done_at := Time.get_unix_time_from_system() for m in group: ms.pending.erase(m) + ms.heat.erase(m) + if mega_cooldown > 0.0: + ms.cooldown_until[m] = done_at + mega_cooldown _save(ms) Term.say("map %d: megas %s (%d) render %.1fs upload %.1fs | %s" % [ms.def.id, group[0], group.size(), (t1 - t0) / 1000.0, (Time.get_ticks_msec() - t1) / 1000.0, res["text"]]) return true diff --git a/tests/run_tests.gd b/tests/run_tests.gd index bb71f6d..61a3da9 100644 --- a/tests/run_tests.gd +++ b/tests/run_tests.gd @@ -29,6 +29,8 @@ func _initialize() -> void: _test_config() _test_live_feed() _test_watch_queue() + _test_dirty_feed() + _test_watch_flood() print("%d checks, %d failed" % [_checks, _fails]) quit(1 if _fails > 0 else 0) @@ -628,3 +630,118 @@ func _test_watch_queue() -> void: _eq("at the limit it is dropped", ms2.pending.has(b), false) _eq("the others stay", ms2.pending.size(), 2) _eq("no count left", ms2.attempts.is_empty(), true) + + +# --- dirty feed (block-change events) ---------------------------------------------------------------------------- + + +func _test_dirty_feed() -> void: + var msg = JSON.parse_string('{"t":"dirty","worlds":{"main":{"bukkit":[[1,2],[3,4]],"worldedit":[[3,4],[5,6]]},"nether":{"bukkit":"junk"}}}') + var parsed := DirtyFeed.parse_dirty(msg) + _eq("worlds parsed", parsed.keys(), ["main"]) + _eq("chunks of both sources merged", parsed["main"].size(), 3) + _ok("chunk kept", parsed["main"].has(Vector2i(5, 6))) + _eq("bad message", DirtyFeed.parse_dirty({"t": "dirty"}), {}) + _eq("bad entries dropped", DirtyFeed.parse_dirty({"worlds": {"w": {"bukkit": [["1", 2], [1, 2, 3], [7, 8]]}}}), {"w": [Vector2i(7, 8)]}) + + var feed := DirtyFeed.new() + feed._token = "secret" + var c := {"peer": WebSocketPeer.new(), "authed": false, "deadline": 0} + feed._message(c, '{"t":"dirty","worlds":{"main":{"bukkit":[[0,0]]}}}') + _eq("dirty before auth is dropped", feed.queued(), 0) + feed._message(c, '{"t":"auth","token":"wrong"}') + _eq("wrong token does not authenticate", c["authed"], false) + feed._message(c, '{"t":"auth","token":"secret"}') + _eq("token authenticates", c["authed"], true) + feed._message(c, '{"t":"dirty","worlds":{"main":{"bukkit":[[0,0],[1,1]]}}}') + _eq("dirty after auth is queued", feed.queued(), 2) + var drained := feed.drain() + _eq("drained world", drained.keys(), ["main"]) + _eq("queue empty after drain", feed.queued(), 0) + + +# --- flood control of the resident updater ----------------------------------------------------------------------- + + +func _test_watch_flood() -> void: + var state := TMP.path_join("state") + DirAccess.make_dir_recursive_absolute(state) + DirAccess.remove_absolute(state.path_join("watch-8.json")) + var def := MapDef.new() + def.id = 8 + def.world = "main" + var job := WatchJob.new() + _ok("map added", job.add(def, state)) + var ms: WatchJob.MapState = job.maps[0] + var now := 10_000.0 + + # merging events: first queued time wins, repeats add heat, the Anvil scan adds none + var chunks: Array[Vector2i] = [Vector2i(0, 0)] + var offered := job._offer(ms, chunks, now, true) + _ok("megas offered", offered > 0) + _eq("pending matches the offer", ms.pending.size(), offered) + var mega: Vector2i = ms.pending.keys()[0] + _eq("offered again adds nothing new", job._offer(ms, chunks, now + 50.0, true), 0) + _eq("first queued time kept", ms.pending[mega], now) + _eq("heat counted", int(ms.heat.get(mega, 0)), 1) + job._offer(ms, chunks, now + 60.0, false) + _eq("the scan adds no heat", int(ms.heat.get(mega, 0)), 1) + + # cooldown: a mega inside its cooldown is skipped, a stale one is not + ms.pending.clear() + ms.heat.clear() + var a := Vector2i(10, 10) + var b := Vector2i(11, 10) + ms.pending[a] = now + ms.pending[b] = now + ms.cooldown_until[a] = now + 100.0 + _eq("cooldown skips", job._next_group(ms, [a, b], now), [b]) + ms.pending[a] = now - job.stale_after - 1.0 + _eq("stale beats cooldown", job._next_group(ms, [a, b], now), [a, b]) + ms.cooldown_until.clear() + + # reserved seat: the oldest queued mega leads the batch even when it ranks last + ms.pending.clear() + var x := Vector2i(20, 20) + var y := Vector2i(21, 20) + var z := Vector2i(22, 20) + ms.pending[x] = now - 10.0 + ms.pending[y] = now - 300.0 + ms.pending[z] = now - 100.0 + var group := job._next_group(ms, [x, y, z], now) + _eq("oldest leads the batch", group[0], y) + _eq("everybody fits", group.size(), 3) + + # hot cap: with two seats, at most one hot mega rides along + var small := WatchJob.new() + small.max_megas = 2 + _ok("map added", small.add(def, state)) + var sms: WatchJob.MapState = small.maps[0] + var h1 := Vector2i(30, 30) + var h2 := Vector2i(31, 30) + var n1 := Vector2i(32, 30) + for m in [h1, h2, n1]: + sms.pending[m] = now + sms.heat[h1] = WatchJob.HOT_HEAT + 2 + sms.heat[h2] = WatchJob.HOT_HEAT + 2 + _eq("hot cap leaves the second hot one out", small._next_group(sms, [h1, h2, n1], now), [h1, n1]) + + # bbox order: row by row, nothing dropped + ms.pending.clear() + var p := Vector2i(5, 9) + var q := Vector2i(7, 8) + var r := Vector2i(6, 8) + for m in [p, q, r]: + ms.pending[m] = now + _eq("bbox works in row order", job._next_group_bbox(ms, now), [r, q, p]) + _eq("bbox is the extent", job._pending_bbox(ms), [Vector2i(5, 8), Vector2i(7, 9)]) + + # cooldown and heat survive a restart + ms.cooldown_until[p] = now + 240.0 + ms.heat[q] = 4 + job._save(ms) + var again := WatchJob.new() + _ok("map added from the saved state", again.add(def, state)) + var ms2: WatchJob.MapState = again.maps[0] + _eq("cooldown survives a restart", float(ms2.cooldown_until.get(p, 0.0)), now + 240.0) + _eq("heat survives a restart", int(ms2.heat.get(q, 0)), 4)