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
38 changes: 35 additions & 3 deletions scripts/job/dirty_feed.gd
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,20 @@ const MAX_CLIENTS := 8
const MAX_WORLDS := 64
const MAX_CHUNKS_PER_MESSAGE := 1_000_000
const AUTH_MSEC := 10_000
## A peer that stays in STATE_CLOSING longer than this is dropped: it never finished its close
## handshake, and left alone it would hold one of the MAX_CLIENTS slots forever.
const CLOSING_MSEC := 5_000

var _server := TCPServer.new()
var _token := ""
var _clients: Array = [] # {peer: WebSocketPeer, authed: bool, deadline: int (ticks msec)}
var _clients: Array = [] # {peer: WebSocketPeer, authed: bool, deadline: int (ticks msec), closing_since: int}
var _queue := {} # world -> {Vector2i: true}
var _connected := false
## Authenticated dirty messages and their chunks since the last received_counts() call. The queue
## alone cannot show receipt: chunks for mega tiles the watch already queued leave no trace in it.
var _received_messages := 0
var _received_chunks := 0
var _auth_rejected := 0


## Starts listening. Returns false (and never listens) without a token or when the port is taken.
Expand Down Expand Up @@ -52,14 +60,15 @@ func poll() -> void:
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})
_clients.append({"peer": peer, "authed": false, "deadline": Time.get_ticks_msec() + AUTH_MSEC, "closing_since": 0})
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:
c["closing_since"] = 0
while peer.get_available_packet_count() > 0:
_message(c, peer.get_packet().get_string_from_utf8())
alive.append(c)
Expand All @@ -69,7 +78,14 @@ func poll() -> void:
else:
alive.append(c)
WebSocketPeer.STATE_CLOSING:
alive.append(c)
var since := int(c.get("closing_since", 0))
if since == 0:
c["closing_since"] = now
alive.append(c)
elif now - since > CLOSING_MSEC:
peer.close()
else:
alive.append(c)
_clients = alive


Expand All @@ -81,16 +97,22 @@ func _message(c: Dictionary, text: String) -> void:
if msg.get("t") is String and msg["t"] == "auth" and msg.get("token") is String and msg["token"] == _token:
c["authed"] = true
else:
_auth_rejected += 1
Term.say("dirty feed: auth rejected (%d total)" % _auth_rejected)
(c["peer"] as WebSocketPeer).close()
return
if msg.get("t") is String and msg["t"] == "dirty":
var parsed := parse_dirty(msg)
var n := 0
for world: String in parsed:
n += (parsed[world] as Array).size()
if not _queue.has(world):
_queue[world] = {}
var seen: Dictionary = _queue[world]
for chunk in parsed[world]:
seen[chunk] = true
_received_messages += 1
_received_chunks += n


## The chunks of one dirty message: world -> Array[Vector2i]. Bad entries are dropped, and a message is
Expand Down Expand Up @@ -155,6 +177,16 @@ func queued() -> int:
return n


## [messages, chunks] received from authenticated connections since the last call; resets both
## counters. Read it together with drain(), once per watch cycle: receipt is the fact that a
## message arrived at all, which the queue cannot show (see _received_messages).
func received_counts() -> Array:
var out := [_received_messages, _received_chunks]
_received_messages = 0
_received_chunks = 0
return out


## Connections that completed the token check.
func authenticated() -> int:
var n := 0
Expand Down
14 changes: 13 additions & 1 deletion scripts/job/watch_job.gd
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const MAX_ATTEMPTS := 3
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
## The heat penalty stops growing here: past HOT_HEAT a mega tile is already as hot as it gets, and an
## uncapped penalty would sink a spot that changes all the time (a fire, say) behind everything else
## until it goes stale, no matter how long it has already waited within that window.
const HEAT_PENALTY_CAP := 6.0 # HOT_HEAT * HEAT_DISTANCE

class MapState:
var def: MapDef
Expand Down Expand Up @@ -237,17 +241,25 @@ func _drain_dirty(now: float) -> void:
if dirty_feed == null:
return
var events: Dictionary = dirty_feed.drain()
var received: Array = dirty_feed.received_counts()
var added_total := 0
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)
added_total += added
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)
# Receipt and queueing are different facts: a cycle that received events says so even when every
# mega tile was already pending (added == 0), so "nothing arrived" and "arrived, already queued"
# can be told apart in the log.
if int(received[0]) > 0:
Term.say("dirty feed: %d messages / %d chunks received, %d new mega tiles (%d pending)" % [int(received[0]), int(received[1]), added_total, _pending_total()])


## smaller = sooner
Expand All @@ -261,7 +273,7 @@ func _rank(ms: MapState, m: Vector2i, queued: float, now: float) -> float:
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())
# 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
return best + queued * 1e-10 + minf(float(int(ms.heat.get(m, 0))) * HEAT_DISTANCE, HEAT_PENALTY_CAP)


## Coroutine: `await watch.run()`.
Expand Down
11 changes: 11 additions & 0 deletions tests/run_tests.gd
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,11 @@ func _test_dirty_feed() -> void:
_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)
_eq("received counted", feed.received_counts(), [1, 2])
_eq("received counts reset by reading", feed.received_counts(), [0, 0])
feed._message(c, '{"t":"dirty","worlds":{"main":{"bukkit":[[0,0]]}}}')
_eq("a repeat dirty counts as received", feed.received_counts(), [1, 1])
_eq("a repeat dirty queues nothing new", feed.queued(), 2)
var drained := feed.drain()
_eq("drained world", drained.keys(), ["main"])
_eq("queue empty after drain", feed.queued(), 0)
Expand Down Expand Up @@ -727,6 +732,12 @@ func _test_watch_flood() -> void:
job._offer(ms, chunks, now + 60.0, false)
_eq("the scan adds no heat", int(ms.heat.get(mega, 0)), 1)

# heat penalty cap: heat far past the cap ranks the same as heat at the cap
ms.heat[mega] = WatchJob.HOT_HEAT
var rank_at_cap := job._rank(ms, mega, now, now)
ms.heat[mega] = 1000
_eq("heat penalty is capped", job._rank(ms, mega, now, now), rank_at_cap)

# cooldown: a mega inside its cooldown is skipped, a stale one is not
ms.pending.clear()
ms.heat.clear()
Expand Down
Loading