3 Commits
24 changed files with 532 additions and 112 deletions

No files matched your search

+2 -1
View File
@@ -1,7 +1,8 @@
.idea
pzlibs
lib
.emmyrc.json
.*/
scripts
*.md
@@ -12,6 +12,7 @@ local MAX_LIMIT = 200
function RDB_OpAuditLogGet.register()
RDB_OpRegistry.register("get_audit_log", {
core = true,
handler = function(args)
local limit = DEFAULT_LIMIT
if type(args.limit) == "number" then
@@ -15,6 +15,7 @@ end
function RDB_OpBridgeStatus.register()
RDB_OpRegistry.register("get_bridge_status", {
core = true,
handler = function(_)
local bootedAt = RDB_Bootstrap.getBootTimestamp()
local now = getTimestampMs()
@@ -0,0 +1,13 @@
-- Registration deferred to register(), called from RDB_Bootstrap's
-- onServerStarted, see RDB_OpWorldGetStats.lua.
RDB_OpListOps = {}
function RDB_OpListOps.register()
RDB_OpRegistry.register("list_ops", {
core = true,
handler = function(_)
return true, { ops = RDB_OpRegistry.listAll() }
end,
})
end
@@ -5,6 +5,7 @@ RDB_OpPlayerGet = {}
function RDB_OpPlayerGet.register()
RDB_OpRegistry.register("get_player", {
core = true,
argsSchema = { id = "string" },
handler = function(args)
local snapshot = RDB_PlayerSnapshot.get(args.id)
@@ -12,6 +12,7 @@ local MAX_LIMIT = 200
function RDB_OpPlayerList.register()
RDB_OpRegistry.register("list_players", {
core = true,
handler = function(args)
local all = RDB_PlayerSnapshot.listAll()
@@ -0,0 +1,21 @@
-- Observability into RDB_RequestQueue (Framework.md section 4): lets both
-- admins and a client tuning its own batch size see the live queue state.
--
-- Registration deferred to register(), called from RDB_Bootstrap's
-- onServerStarted, see RDB_OpWorldGetStats.lua.
RDB_OpQueueStatus = {}
function RDB_OpQueueStatus.register()
RDB_OpRegistry.register("get_queue_status", {
core = true,
handler = function(_)
return true, {
depth = RDB_RequestQueue.depth(),
oldestEnqueuedAt = RDB_RequestQueue.oldestEnqueuedAt(),
requestsPerTick = RDB_Config.get("RequestsPerTick"),
maxQueueDepth = RDB_Config.get("MaxQueueDepth"),
}
end,
})
end
@@ -5,6 +5,7 @@ RDB_OpServerSave = {}
function RDB_OpServerSave.register()
RDB_OpRegistry.register("save_server", {
core = true,
handler = function(_)
local ok = pcall(function() GameWindow.save(true) end)
if not ok then
@@ -0,0 +1,28 @@
-- Remote admin toggle for third-party-registered ops (Framework.md section
-- 3b). Always core itself, along with list_ops -- disabling this op would
-- strand an admin unable to re-enable anything else without a restart.
--
-- Registration deferred to register(), called from RDB_Bootstrap's
-- onServerStarted, see RDB_OpWorldGetStats.lua.
RDB_OpSetOpEnabled = {}
function RDB_OpSetOpEnabled.register()
RDB_OpRegistry.register("set_op_enabled", {
core = true,
argsSchema = { name = "string", enabled = "boolean" },
handler = function(args)
local ok, reason = RDB_OpRegistry.setEnabled(args.name, args.enabled)
if not ok then
if reason == "core" then
return false, RDB_Constants.ERROR_CODES.CORE_OP_PROTECTED,
"Op '" .. args.name .. "' is a core op and cannot be disabled."
end
return false, RDB_Constants.ERROR_CODES.OP_NOT_ALLOWED,
"Unknown operation: " .. args.name
end
return true, { name = args.name, enabled = args.enabled }
end,
})
end
@@ -10,6 +10,7 @@ RDB_OpWorldGetStats = {}
function RDB_OpWorldGetStats.register()
RDB_OpRegistry.register("get_world_stats", {
core = true,
handler = function(_)
return true, RDB_WorldStats.collect()
end,
@@ -3,7 +3,7 @@
-- (bad payload, unknown op, rate-limited, etc). Persisted as a bounded
-- ring buffer via ModData, plus a console line for live tailing.
require("RconDataBridge.RDB_Log")
require("RconDataBridge/RDB_Log")
RDB_AuditLog = {}
@@ -1,19 +1,23 @@
require("RconDataBridge.RDB_Constants")
require("RconDataBridge.RDB_Log")
require("RconDataBridge.RDB_Json")
require("RconDataBridge.RDB_Base64")
require("RconDataBridge.RDB_OptionsRegistry")
require("RconDataBridge.RDB_Config")
require("RconDataBridge.RDB_OpRegistry")
require("RconDataBridge.RDB_RequestPipeline")
require("RconDataBridge.RDB_WorldStats")
require("RconDataBridge.RDB_PlayerSnapshot")
require("RconDataBridge.Ops.RDB_OpWorldGetStats")
require("RconDataBridge.Ops.RDB_OpPlayerGet")
require("RconDataBridge.Ops.RDB_OpPlayerList")
require("RconDataBridge.Ops.RDB_OpServerSave")
require("RconDataBridge.Ops.RDB_OpBridgeStatus")
require("RconDataBridge.Ops.RDB_OpAuditLogGet")
require("RconDataBridge/RDB_Constants")
require("RconDataBridge/RDB_Log")
require("RconDataBridge/RDB_Json")
require("RconDataBridge/RDB_Base64")
require("RconDataBridge/RDB_OptionsRegistry")
require("RconDataBridge/RDB_Config")
require("RconDataBridge/RDB_OpRegistry")
require("RconDataBridge/RDB_RequestQueue")
require("RconDataBridge/RDB_RequestPipeline")
require("RconDataBridge/RDB_WorldStats")
require("RconDataBridge/RDB_PlayerSnapshot")
require("RconDataBridge/Ops/RDB_OpWorldGetStats")
require("RconDataBridge/Ops/RDB_OpPlayerGet")
require("RconDataBridge/Ops/RDB_OpPlayerList")
require("RconDataBridge/Ops/RDB_OpServerSave")
require("RconDataBridge/Ops/RDB_OpBridgeStatus")
require("RconDataBridge/Ops/RDB_OpAuditLogGet")
require("RconDataBridge/Ops/RDB_OpListOps")
require("RconDataBridge/Ops/RDB_OpSetOpEnabled")
require("RconDataBridge/Ops/RDB_OpQueueStatus")
RDB_Bootstrap = {}
@@ -60,12 +64,21 @@ local function registerOps()
RDB_OpServerSave.register()
RDB_OpBridgeStatus.register()
RDB_OpAuditLogGet.register()
RDB_OpListOps.register()
RDB_OpSetOpEnabled.register()
RDB_OpQueueStatus.register()
end
-- `queueing` lets a v2 client size its own batches against the live server
-- config instead of hardcoding assumptions (Framework.md section 4).
local function publishProtocolVersion()
local json = RDB_Json.encode({
version = RDB_Config.get("ProtocolVersion"),
ops = RDB_OpRegistry.listNames(),
version = RDB_Config.get("ProtocolVersion"),
ops = RDB_OpRegistry.listNames(),
queueing = {
maxQueueDepth = RDB_Config.get("MaxQueueDepth"),
requestsPerTick = RDB_Config.get("RequestsPerTick"),
},
})
RDB_OptionsRegistry.set(RDB_Constants.OPT.PROTOCOL_VERSION, json)
@@ -17,7 +17,7 @@
-- milliseconds, belong in the one caller that needs the converted unit, not
-- here -- see RDB_Idempotency.)
require("RconDataBridge.RDB_Constants")
require("RconDataBridge/RDB_Constants")
RDB_Config = {}
@@ -41,5 +41,11 @@ function RDB_Config.getAll()
maxPayloadBytes = RDB_Config.get("MaxPayloadBytes"),
rateLimitMaxRequests = RDB_Config.get("RateLimitMaxRequests"),
rateLimitWindowSeconds = RDB_Config.get("RateLimitWindowSeconds"),
rosterPollTicks = RDB_Config.get("RosterPollTicks"),
pollIntervalIdleTicks = RDB_Config.get("PollIntervalIdleTicks"),
pollIntervalActiveTicks = RDB_Config.get("PollIntervalActiveTicks"),
activeWindowSeconds = RDB_Config.get("ActiveWindowSeconds"),
requestsPerTick = RDB_Config.get("RequestsPerTick"),
maxQueueDepth = RDB_Config.get("MaxQueueDepth"),
}
end
@@ -9,9 +9,9 @@
-- first-ever response back on every call, since a low-traffic server would
-- rarely reach MAX_ENTRIES and trigger the count-based eviction below.
require("RconDataBridge.RDB_Constants")
require("RconDataBridge.RDB_Config")
require("RconDataBridge.RDB_Log")
require("RconDataBridge/RDB_Constants")
require("RconDataBridge/RDB_Config")
require("RconDataBridge/RDB_Log")
RDB_Idempotency = {}
@@ -84,3 +84,25 @@ function RDB_Idempotency.put(id, response)
s[id] = { response = response, ts = getTimestampMs() }
prune(s)
end
-- Every non-expired cached response, newest first. Backs
-- RDB_RequestPipeline's Response publish (Framework.md section 2): a v2
-- client's poll rate is independent of the server's drain rate, so a
-- single "this tick's completions only" publish can get overwritten by the
-- next tick before a slower-polling client ever reads it. Publishing the
-- full still-valid cache instead means any response stays retrievable for
-- its full IdempotencyTtlSeconds window, not just the one tick it
-- completed on. Newest-first ordering lets a caller with limited payload
-- budget greedily keep the freshest entries when trimming.
function RDB_Idempotency.getAllCurrent()
local s = ensureStore()
local out = {}
for _, entry in pairs(s) do
if not isExpired(entry) then
out[#out + 1] = entry
end
end
table.sort(out, function(a, b) return (a.ts or 0) > (b.ts or 0) end)
return out
end
@@ -1,22 +1,53 @@
-- Table-driven op registry. This is the allowlist: dispatch only ever looks
-- up a handler function by exact op name in this table -- there is no
-- dynamic _G[name]() call and no load()/loadstring() anywhere in this mod.
--
-- Also the plugin extension point for other PZ mods (see Framework.md
-- section 3, API.md): a third-party mod requires this file and calls
-- .register()/.unregister() from its own Events.OnServerStarted handler,
-- same deferred-registration pattern this repo's own Ops/*.lua use.
require("RconDataBridge.RDB_Constants")
require("RconDataBridge/RDB_Constants")
RDB_OpRegistry = {}
local handlers = {}
-- def: { handler = function(args) -> ok, dataOrErrCode[, errMessage], argsSchema = {fieldName = "type", ...} }
-- def: { handler = function(args) -> ok, dataOrErrCode[, errMessage],
-- argsSchema = {fieldName = "type", ...}, core = true|false }
-- `core` ops (this repo's own status/audit/meta ops) can't be remotely
-- disabled via set_op_enabled -- see RDB_OpRegistry.setEnabled.
function RDB_OpRegistry.register(name, def)
if def.enabled == nil then
def.enabled = true
end
handlers[name] = def
end
function RDB_OpRegistry.unregister(name)
handlers[name] = nil
end
function RDB_OpRegistry.isRegistered(name)
return handlers[name] ~= nil
end
-- Returns false, "not found" if `name` isn't registered at all, or
-- false, "core" if it's registered but protected from remote disable.
-- Enabling a core op (or any op) always succeeds.
function RDB_OpRegistry.setEnabled(name, enabled)
local def = handlers[name]
if not def then
return false, "not found"
end
if def.core and not enabled then
return false, "core"
end
def.enabled = enabled
return true
end
function RDB_OpRegistry.listNames()
local names = {}
for name in pairs(handlers) do
@@ -26,13 +57,24 @@ function RDB_OpRegistry.listNames()
return names
end
-- Full introspection for the list_ops meta-op: name/core/enabled per
-- registered op, not just names.
function RDB_OpRegistry.listAll()
local out = {}
for _, name in ipairs(RDB_OpRegistry.listNames()) do
local def = handlers[name]
out[#out + 1] = { name = name, core = def.core == true, enabled = def.enabled ~= false }
end
return out
end
-- Validates args against the op's declared schema (shallow: field presence +
-- Lua type of top-level fields), then dispatches. Returns:
-- ok, data on success
-- false, errCode, errMessage on failure (schema or handler-reported error)
function RDB_OpRegistry.dispatch(name, args)
local def = handlers[name]
if not def then
if not def or def.enabled == false then
return false, RDB_Constants.ERROR_CODES.OP_NOT_ALLOWED, "Unknown or disallowed operation: " .. tostring(name)
end
@@ -25,8 +25,8 @@
-- the request pipeline diffs the raw stored string for change detection
-- and needs to see it either way, decode failure included.
require("RconDataBridge.RDB_Log")
require("RconDataBridge.RDB_Base64")
require("RconDataBridge/RDB_Log")
require("RconDataBridge/RDB_Base64")
RDB_OptionsRegistry = {}
@@ -6,15 +6,17 @@
-- of truth for offline players..
--
-- Connect/disconnect detection: no server-side connect/disconnect event was
-- found in the stub trees, so this polls getOnlinePlayers() on the same
-- tick throttle as the request pipeline and diffs against the last-known
-- online set.
-- found in the stub trees, so this polls getOnlinePlayers() on its own
-- RosterPollTicks throttle (separate from RDB_RequestPipeline's adaptive
-- request-queue interval -- roster diffing isn't request-driven, so it has
-- no "activity" signal to speed up around) and diffs against the
-- last-known online set.
require("RconDataBridge.RDB_Constants")
require("RconDataBridge.RDB_Log")
require("RconDataBridge.RDB_Json")
require("RconDataBridge.RDB_OptionsRegistry")
require("RconDataBridge.RDB_Config")
require("RconDataBridge/RDB_Constants")
require("RconDataBridge/RDB_Log")
require("RconDataBridge/RDB_Json")
require("RconDataBridge/RDB_OptionsRegistry")
require("RconDataBridge/RDB_Config")
RDB_PlayerSnapshot = {}
@@ -134,7 +136,7 @@ local initialized = false
local function onTick()
tickCounter = tickCounter + 1
if tickCounter < RDB_Config.get("PollEveryTicks") then
if tickCounter < RDB_Config.get("RosterPollTicks") then
return
end
@@ -1,22 +1,34 @@
-- Polls RconDataBridge_Request for changes (there is no "option changed"
-- event in the PZ Lua API) and runs the full request/response pipeline.
-- Every outcome, including every rejection, is audited.
-- event in the PZ Lua API). A write is decoded as a JSON array of request
-- envelopes ("v2" protocol -- see Framework.md section 2) and the whole
-- batch is enqueued into RDB_RequestQueue rather than processed inline, so
-- a second changeoption before the first batch finishes draining can never
-- clobber it the way v1's single-object mailbox could. Up to
-- RequestsPerTick queued envelopes are dequeued and dispatched per poll;
-- every outcome, including every rejection, is audited.
--
-- Poll cadence is adaptive, not fixed (see Framework.md section 1):
-- PollIntervalActiveTicks while there's been request traffic within the
-- last ActiveWindowSeconds, decaying back to the slower
-- PollIntervalIdleTicks once things go quiet.
require("RconDataBridge.RDB_Constants")
require("RconDataBridge.RDB_Json")
require("RconDataBridge.RDB_Base64")
require("RconDataBridge.RDB_Log")
require("RconDataBridge.RDB_OptionsRegistry")
require("RconDataBridge.RDB_Config")
require("RconDataBridge.RDB_Security")
require("RconDataBridge.RDB_Idempotency")
require("RconDataBridge.RDB_AuditLog")
require("RconDataBridge.RDB_OpRegistry")
require("RconDataBridge/RDB_Constants")
require("RconDataBridge/RDB_Json")
require("RconDataBridge/RDB_Base64")
require("RconDataBridge/RDB_Log")
require("RconDataBridge/RDB_OptionsRegistry")
require("RconDataBridge/RDB_Config")
require("RconDataBridge/RDB_Security")
require("RconDataBridge/RDB_Idempotency")
require("RconDataBridge/RDB_AuditLog")
require("RconDataBridge/RDB_OpRegistry")
require("RconDataBridge/RDB_RequestQueue")
RDB_RequestPipeline = {}
local lastSeenRaw = nil
local tickCounter = 0
local lastSeenRaw = nil
local tickCounter = 0
local lastActivityAt = 0
local function buildOkResponse(id, data)
return {
@@ -36,11 +48,6 @@ local function buildErrorResponse(id, code, message)
}
end
local function publishResponse(response)
RDB_OptionsRegistry.set(RDB_Constants.OPT.RESPONSE, RDB_Json.encode(response))
RDB_OptionsRegistry.set(RDB_Constants.OPT.LAST_RESPONSE, tostring(getTimestampMs()))
end
local function audit(id, op, ok, code)
RDB_AuditLog.record({ id = id, op = op, ok = ok, code = code })
end
@@ -58,46 +65,36 @@ local function safeDispatch(op, args)
return a, b, c
end
-- Handles one raw request string end to end. raw is base64: RCON's
-- changeoption command strips every literal double-quote character from
-- every argument (see RESEARCH_LOG.md), so a client can't send raw JSON --
-- base64 has no quote characters in its alphabet and survives intact.
local function processRequest(rawBase64)
local raw, b64Err = RDB_Base64.decode(rawBase64)
if b64Err then
local response = buildErrorResponse("", RDB_Constants.ERROR_CODES.SCHEMA_ERROR, "Invalid base64: " .. b64Err)
publishResponse(response)
audit("", "", false, RDB_Constants.ERROR_CODES.SCHEMA_ERROR)
return
end
local function extractId(decoded)
return (type(decoded) == "table" and type(decoded.id) == "string") and decoded.id or ""
end
local sizeOk, sizeCode, sizeMsg = RDB_Security.checkPayloadSize(raw)
if not sizeOk then
local response = buildErrorResponse("", sizeCode, sizeMsg)
publishResponse(response)
audit("", "", false, sizeCode)
return
end
local decoded, decodeErr = RDB_Json.decode(raw)
if decodeErr then
local response = buildErrorResponse("", RDB_Constants.ERROR_CODES.SCHEMA_ERROR, "Invalid JSON: " .. decodeErr)
publishResponse(response)
audit("", "", false, RDB_Constants.ERROR_CODES.SCHEMA_ERROR)
return
end
-- Empty object ({}) is the option's rest state, not a real request.
if type(decoded) == "table" and decoded.v == nil and decoded.id == nil and decoded.op == nil then
return
-- A response with a real id is cached so it survives into future polls (see
-- flushResponses below) -- an id-less response (top-level payload errors
-- that never got far enough to decode an id) has nothing a client could
-- correlate it against anyway, so it only ever rides along on this tick's
-- publish, same as v1's single-mailbox behavior for that one case.
local function cacheOrTransient(response, transientBucket)
if response.id ~= "" then
RDB_Idempotency.put(response.id, response)
else
transientBucket[#transientBucket + 1] = response
end
end
-- Runs one already-dequeued envelope end to end. Never publishes directly --
-- every response ends up cached (via RDB_Idempotency.put, id is guaranteed
-- non-empty past validateEnvelope) and the caller (onTick) republishes the
-- full accumulated Response payload, see flushResponses.
local function processEnvelope(decoded)
local envelopeOk, envelopeCode, envelopeMsg = RDB_Security.validateEnvelope(decoded)
if not envelopeOk then
local id = (type(decoded) == "table" and type(decoded.id) == "string") and decoded.id or ""
local id = extractId(decoded)
local response = buildErrorResponse(id, envelopeCode, envelopeMsg)
publishResponse(response)
audit(id, (type(decoded) == "table" and decoded.op) or "", false, envelopeCode)
if id ~= "" then
RDB_Idempotency.put(id, response)
end
return
end
@@ -105,8 +102,6 @@ local function processRequest(rawBase64)
if RDB_Idempotency.has(id) then
local cached = RDB_Idempotency.get(id)
publishResponse(cached)
local cachedErrCode = nil
if not cached.ok then
cachedErrCode = cached.error and cached.error.code
@@ -118,8 +113,8 @@ local function processRequest(rawBase64)
local rateOk, rateCode, rateMsg = RDB_Security.checkRateLimit()
if not rateOk then
local response = buildErrorResponse(id, rateCode, rateMsg)
publishResponse(response)
audit(id, op, false, rateCode)
RDB_Idempotency.put(id, response)
return
end
@@ -132,7 +127,6 @@ local function processRequest(rawBase64)
end
RDB_Idempotency.put(id, response)
publishResponse(response)
local errCode = nil
if not dispatchOk then
@@ -141,23 +135,170 @@ local function processRequest(rawBase64)
audit(id, op, dispatchOk, errCode)
end
-- Decodes one raw (base64) Request write into an array of envelopes and
-- tries to enqueue them as a whole batch. Returns any id-less transient
-- responses (a malformed top-level payload has no envelope id to cache
-- against) plus whether anything worth republishing over happened at all --
-- the caller uses that second value both to decide whether to touch the
-- Response option and as the "activity" signal for adaptive polling.
local function ingest(rawBase64)
local transient = {}
local raw, b64Err = RDB_Base64.decode(rawBase64)
if b64Err then
cacheOrTransient(buildErrorResponse("", RDB_Constants.ERROR_CODES.SCHEMA_ERROR, "Invalid base64: " .. b64Err), transient)
return transient, true
end
local sizeOk, sizeCode, sizeMsg = RDB_Security.checkPayloadSize(raw)
if not sizeOk then
cacheOrTransient(buildErrorResponse("", sizeCode, sizeMsg), transient)
return transient, true
end
local decoded, decodeErr = RDB_Json.decode(raw)
if decodeErr then
cacheOrTransient(buildErrorResponse("", RDB_Constants.ERROR_CODES.SCHEMA_ERROR, "Invalid JSON: " .. decodeErr), transient)
return transient, true
end
if type(decoded) ~= "table" then
cacheOrTransient(buildErrorResponse("", RDB_Constants.ERROR_CODES.SCHEMA_ERROR,
"Request must be a JSON array of envelopes"), transient)
return transient, true
end
-- A lone envelope-shaped object (v1's request shape) is a plausible
-- migration mistake -- called out explicitly rather than silently
-- treated as a zero-length batch, which ipairs() over a non-array table
-- would otherwise do.
if decoded.v ~= nil or decoded.id ~= nil or decoded.op ~= nil then
cacheOrTransient(buildErrorResponse(extractId(decoded), RDB_Constants.ERROR_CODES.SCHEMA_ERROR,
"Request must be a JSON array of envelopes in protocol v2, not a single object"), transient)
return transient, true
end
-- Empty array/object ({} / []) is the option's rest state, not a real
-- request -- both decode to an identical empty Lua table.
local envelopes = decoded
if #envelopes == 0 then
return transient, false
end
-- Note: if a rejected batch is itself large enough that all of its
-- QUEUE_FULL responses can't fit in one Response payload (see
-- buildResponsePayload's budget trim), only the newest subset is
-- visible on the very next publish -- the rest stay cached and surface
-- once something else's activity triggers a later publish with room
-- for them. Not worth solving with more machinery: the correct client
-- reaction to QUEUE_FULL is "submit a smaller batch," not "wait for
-- every individual rejection to eventually rotate into view."
if not RDB_RequestQueue.tryEnqueueBatch(envelopes) then
for _, envelope in ipairs(envelopes) do
local id = extractId(envelope)
local response = buildErrorResponse(id, RDB_Constants.ERROR_CODES.QUEUE_FULL,
"Request queue is full; retry the whole batch later.")
audit(id, (type(envelope) == "table" and envelope.op) or "", false, RDB_Constants.ERROR_CODES.QUEUE_FULL)
cacheOrTransient(response, transient)
end
return transient, true
end
return transient, true -- enqueued -- not completed yet, but still activity
end
-- Builds the Response payload: this tick's id-less transient responses
-- first (always fresh, always small in practice), then as many of the
-- still-valid cached responses (newest first) as fit under MaxPayloadBytes
-- -- the same decoded-byte budget the request side enforces, since both
-- directions are bound by the same TextServerOption capacity (see
-- CLAUDE.md). An older response that gets trimmed off here is still
-- retrievable: it stays in the idempotency cache for the rest of its TTL,
-- so a later poll (once newer entries have aged out and freed budget) or a
-- client resending the same id will still find it.
local function buildResponsePayload(transient)
local budget = RDB_Config.get("MaxPayloadBytes")
local payload = {}
local usedBytes = 2 -- "[]"
for _, response in ipairs(transient) do
usedBytes = usedBytes + #RDB_Json.encode(response) + 1
payload[#payload + 1] = response
end
for _, entry in ipairs(RDB_Idempotency.getAllCurrent()) do
local encoded = RDB_Json.encode(entry.response)
if usedBytes + #encoded + 1 > budget then
break
end
usedBytes = usedBytes + #encoded + 1
payload[#payload + 1] = entry.response
end
return payload
end
local function flushResponses(transient)
RDB_OptionsRegistry.set(RDB_Constants.OPT.RESPONSE, RDB_Json.encode(buildResponsePayload(transient)))
RDB_OptionsRegistry.set(RDB_Constants.OPT.LAST_RESPONSE, tostring(getTimestampMs()))
end
local function currentIntervalTicks()
local activeWindowMs = RDB_Config.get("ActiveWindowSeconds") * 1000
if getTimestampMs() - lastActivityAt < activeWindowMs then
return RDB_Config.get("PollIntervalActiveTicks")
end
return RDB_Config.get("PollIntervalIdleTicks")
end
local function onTick()
tickCounter = tickCounter + 1
if tickCounter < RDB_Config.get("PollEveryTicks") then
if tickCounter < currentIntervalTicks() then
return
end
tickCounter = 0
local transientResponses = {}
local activity = false
local raw = RDB_OptionsRegistry.get(RDB_Constants.OPT.REQUEST)
if raw == lastSeenRaw then
if raw ~= lastSeenRaw then
lastSeenRaw = raw
local ok, transient, ingestActivity = pcall(ingest, raw)
if ok then
if ingestActivity then
lastActivityAt = getTimestampMs()
activity = true
end
for _, r in ipairs(transient) do
transientResponses[#transientResponses + 1] = r
end
else
RDB_Log.error("unhandled error ingesting request: " .. tostring(transient))
end
end
local requestsPerTick = RDB_Config.get("RequestsPerTick")
for _ = 1, requestsPerTick do
local envelope = RDB_RequestQueue.dequeue()
if envelope == nil then
break
end
lastActivityAt = getTimestampMs()
activity = true
local ok, err = pcall(processEnvelope, envelope)
if not ok then
RDB_Log.error("unhandled error processing envelope: " .. tostring(err))
end
end
if not activity then
return
end
lastSeenRaw = raw
local ok, err = pcall(processRequest, raw)
if not ok then
RDB_Log.error("unhandled error processing request: " .. tostring(err))
end
flushResponses(transientResponses)
end
local initialized = false
@@ -0,0 +1,63 @@
-- In-memory FIFO of decoded (not yet validated) request envelopes, backing
-- the v2 single-slot batched request protocol: a write to
-- RconDataBridge_Request is an array of envelopes appended to this queue,
-- not a value that overwrites whatever hasn't been processed yet (the v1
-- single-mailbox design silently lost a request under back-to-back writes).
-- See Framework.md section 2.
--
-- Not ModData-persisted: a restart dropping in-flight requests is
-- acceptable (v1's single mailbox never survived a restart either) and
-- avoids a second on-disk store to keep in sync with RDB_Idempotency's.
require("RconDataBridge/RDB_Config")
RDB_RequestQueue = {}
local queue = {}
local head = 1
local tail = 0
function RDB_RequestQueue.depth()
local d = tail - head + 1
return d > 0 and d or 0
end
function RDB_RequestQueue.oldestEnqueuedAt()
if RDB_RequestQueue.depth() == 0 then
return nil
end
return queue[head].enqueuedAt
end
-- Enqueues every element of `envelopes` atomically: if doing so would push
-- depth over MaxQueueDepth, nothing is enqueued at all -- a batch is
-- rejected whole or not at all, so a client never has to guess which part
-- of a submitted batch landed. Returns whether the batch was accepted.
function RDB_RequestQueue.tryEnqueueBatch(envelopes)
local maxDepth = RDB_Config.get("MaxQueueDepth")
if RDB_RequestQueue.depth() + #envelopes > maxDepth then
return false
end
local now = getTimestampMs()
for _, envelope in ipairs(envelopes) do
tail = tail + 1
queue[tail] = { envelope = envelope, enqueuedAt = now }
end
return true
end
-- Returns nil once the queue is empty.
function RDB_RequestQueue.dequeue()
if RDB_RequestQueue.depth() == 0 then
return nil
end
local item = queue[head]
queue[head] = nil
head = head + 1
return item.envelope
end
@@ -5,8 +5,8 @@
-- the same RconDataBridge_Request mailbox. The window is an in-memory sliding
-- log; it does not need to survive a restart.
require("RconDataBridge.RDB_Constants")
require("RconDataBridge.RDB_Config")
require("RconDataBridge/RDB_Constants")
require("RconDataBridge/RDB_Config")
RDB_Security = {}
@@ -1,9 +1,9 @@
-- World telemetry, sourced from zombie.GameTime (getGameTime()).
require("RconDataBridge.RDB_Constants")
require("RconDataBridge.RDB_Log")
require("RconDataBridge.RDB_Json")
require("RconDataBridge.RDB_OptionsRegistry")
require("RconDataBridge/RDB_Constants")
require("RconDataBridge/RDB_Log")
require("RconDataBridge/RDB_Json")
require("RconDataBridge/RDB_OptionsRegistry")
RDB_WorldStats = {}
@@ -6,7 +6,7 @@
RDB_Constants = {}
RDB_Constants.PROTOCOL_VERSION = 1
RDB_Constants.PROTOCOL_VERSION = 2
RDB_Constants.OPT = {
PROTOCOL_VERSION = "RconDataBridge_ProtocolVersion",
@@ -29,4 +29,6 @@ RDB_Constants.ERROR_CODES = {
PLAYER_NOT_FOUND = "PLAYER_NOT_FOUND",
SAVE_FAILED = "SAVE_FAILED",
INTERNAL_ERROR = "INTERNAL_ERROR",
QUEUE_FULL = "QUEUE_FULL",
CORE_OP_PROTECTED = "CORE_OP_PROTECTED",
}
@@ -2,8 +2,18 @@
"Sandbox_RconDataBridge": "RCON Data Bridge",
"Sandbox_RconDataBridge_DebugSelfTest": "Debug Self-Tests",
"Sandbox_RconDataBridge_DebugSelfTest_tooltip": "Run RDB_Json/RDB_Base64 self-tests and log the result on every server boot.",
"Sandbox_RconDataBridge_PollEveryTicks": "Poll Interval (ticks)",
"Sandbox_RconDataBridge_PollEveryTicks_tooltip": "How many server ticks between checks of the request mailbox and the online-player roster. Lower is more responsive, higher is less overhead.",
"Sandbox_RconDataBridge_RosterPollTicks": "Roster Poll Interval (ticks)",
"Sandbox_RconDataBridge_RosterPollTicks_tooltip": "How many server ticks between online-player roster checks (connect/disconnect detection).",
"Sandbox_RconDataBridge_PollIntervalIdleTicks": "Request Poll Interval, Idle (ticks)",
"Sandbox_RconDataBridge_PollIntervalIdleTicks_tooltip": "How many server ticks between request-queue checks when there's been no recent traffic.",
"Sandbox_RconDataBridge_PollIntervalActiveTicks": "Request Poll Interval, Active (ticks)",
"Sandbox_RconDataBridge_PollIntervalActiveTicks_tooltip":"How many server ticks between request-queue checks while recently active (within Active Window). Lower is more responsive, higher is less overhead.",
"Sandbox_RconDataBridge_ActiveWindowSeconds": "Active Window (seconds)",
"Sandbox_RconDataBridge_ActiveWindowSeconds_tooltip": "How long after the last processed request the bridge keeps polling at the Active interval before decaying back to Idle.",
"Sandbox_RconDataBridge_RequestsPerTick": "Requests Processed Per Poll",
"Sandbox_RconDataBridge_RequestsPerTick_tooltip": "How many queued requests are dequeued and processed on each poll.",
"Sandbox_RconDataBridge_MaxQueueDepth": "Max Queue Depth",
"Sandbox_RconDataBridge_MaxQueueDepth_tooltip": "Maximum number of requests allowed to sit in the queue at once. A batch that would exceed this is rejected whole with QUEUE_FULL.",
"Sandbox_RconDataBridge_IdempotencyTtlSeconds": "Idempotency Window (seconds)",
"Sandbox_RconDataBridge_IdempotencyTtlSeconds_tooltip": "How long a repeated request id replays its cached response instead of running again.",
"Sandbox_RconDataBridge_RateLimitMaxRequests": "Rate Limit: Max Requests",
@@ -8,14 +8,64 @@ option RconDataBridge.DebugSelfTest
translation = RconDataBridge_DebugSelfTest,
}
option RconDataBridge.PollEveryTicks
option RconDataBridge.RosterPollTicks
{
type = integer,
min = 1,
max = 300,
default = 30,
page = RconDataBridge,
translation = RconDataBridge_PollEveryTicks,
translation = RconDataBridge_RosterPollTicks,
}
option RconDataBridge.PollIntervalIdleTicks
{
type = integer,
min = 1,
max = 300,
default = 30,
page = RconDataBridge,
translation = RconDataBridge_PollIntervalIdleTicks,
}
option RconDataBridge.PollIntervalActiveTicks
{
type = integer,
min = 1,
max = 300,
default = 3,
page = RconDataBridge,
translation = RconDataBridge_PollIntervalActiveTicks,
}
option RconDataBridge.ActiveWindowSeconds
{
type = integer,
min = 1,
max = 600,
default = 10,
page = RconDataBridge,
translation = RconDataBridge_ActiveWindowSeconds,
}
option RconDataBridge.RequestsPerTick
{
type = integer,
min = 1,
max = 50,
default = 1,
page = RconDataBridge,
translation = RconDataBridge_RequestsPerTick,
}
option RconDataBridge.MaxQueueDepth
{
type = integer,
min = 1,
max = 1000,
default = 50,
page = RconDataBridge,
translation = RconDataBridge_MaxQueueDepth,
}
option RconDataBridge.IdempotencyTtlSeconds