Archived
Compare commits
19
Commits
3bebae73ed
...
v2.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ed40d7017 | ||
|
|
30f5faa9a7 | ||
|
|
726bbe8064 | ||
|
|
68aba1bd47 | ||
|
|
5de8493cef | ||
|
|
ff59e73a0f | ||
|
|
3bd4815ee2 | ||
|
|
807bd9f4ef | ||
|
|
2aaa327853 | ||
|
|
806bd8ae6a | ||
|
|
60c2c718eb | ||
|
|
52abbc5643 | ||
|
|
dd801de28d | ||
|
|
439105ec60 | ||
|
|
b5a9ab3b5d | ||
|
|
854c19dca7 | ||
|
|
3a02db5717 | ||
|
|
9de6799a5e | ||
|
|
b0b4a815c2 |
No files matched your search
+5
-1
@@ -1,7 +1,11 @@
|
||||
.idea
|
||||
|
||||
pzlibs
|
||||
lib
|
||||
.emmyrc.json
|
||||
.*/
|
||||
|
||||
scripts
|
||||
*.md
|
||||
|
||||
luac.out
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
name=RCON Data Bridge
|
||||
id=RconDataBridge
|
||||
description=
|
||||
description=A Project Zomboid server mod enabling richer RCON tooling and automation.
|
||||
poster=poster.png
|
||||
author=Overlord_303
|
||||
modversion=0.1.0
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
+36
@@ -0,0 +1,36 @@
|
||||
-- Returns the most recent audit entries, newest first. RDB_AuditLog.getEntries()
|
||||
-- is a ring buffer in slot order, not chronological order once it's wrapped
|
||||
-- past its capacity, so entries are sorted by ts before slicing.
|
||||
--
|
||||
-- Registration deferred to register(), called from RDB_Bootstrap's
|
||||
-- onServerStarted, see RDB_OpWorldGetStats.lua.
|
||||
|
||||
RDB_OpAuditLogGet = {}
|
||||
|
||||
local DEFAULT_LIMIT = 50
|
||||
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
|
||||
limit = math.min(math.max(1, math.floor(args.limit)), MAX_LIMIT)
|
||||
end
|
||||
|
||||
local entries = {}
|
||||
for _, entry in ipairs(RDB_AuditLog.getEntries()) do
|
||||
entries[#entries + 1] = entry
|
||||
end
|
||||
table.sort(entries, function(a, b) return (a.ts or 0) > (b.ts or 0) end)
|
||||
|
||||
local page = {}
|
||||
for i = 1, math.min(limit, #entries) do
|
||||
page[#page + 1] = entries[i]
|
||||
end
|
||||
|
||||
return true, { entries = page }
|
||||
end,
|
||||
})
|
||||
end
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
---@diagnostic disable: need-check-nil
|
||||
|
||||
-- Registration deferred to register(), called from RDB_Bootstrap's
|
||||
-- onServerStarted, see RDB_OpWorldGetStats.lua.
|
||||
|
||||
RDB_OpBridgeStatus = {}
|
||||
|
||||
-- Mirrors zombie.GameTime.isGamePaused()'s server-side branch exactly
|
||||
-- (decompiled: `GameServer.Players.isEmpty() && ServerOptions.instance.pauseEmpty.getValue()`),
|
||||
-- true precisely when RDB_RequestPipeline would be relying on Events.OnTickEvenPaused
|
||||
-- instead of Events.OnTick to even see this request.
|
||||
local function isPaused()
|
||||
return ServerOptions.instance:getBoolean("PauseEmpty") and getOnlinePlayers():size() == 0
|
||||
end
|
||||
|
||||
function RDB_OpBridgeStatus.register()
|
||||
RDB_OpRegistry.register("get_bridge_status", {
|
||||
core = true,
|
||||
handler = function(_)
|
||||
local bootedAt = RDB_Bootstrap.getBootTimestamp()
|
||||
local now = getTimestampMs()
|
||||
|
||||
return true, {
|
||||
version = RDB_Config.get("ProtocolVersion"),
|
||||
bootedAt = bootedAt,
|
||||
uptimeSeconds = (now - bootedAt) / 1000,
|
||||
paused = isPaused(),
|
||||
rateLimit = RDB_Security.getRateLimitStatus(),
|
||||
config = RDB_Config.getAll(),
|
||||
}
|
||||
end,
|
||||
})
|
||||
end
|
||||
+13
@@ -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
|
||||
+1
@@ -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)
|
||||
|
||||
+1
@@ -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()
|
||||
|
||||
|
||||
+21
@@ -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
|
||||
+1
@@ -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
|
||||
|
||||
+28
@@ -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
|
||||
+1
@@ -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,
|
||||
|
||||
+1
-1
@@ -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 = {}
|
||||
|
||||
|
||||
+51
-23
@@ -1,20 +1,34 @@
|
||||
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/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 = {}
|
||||
|
||||
local bootTimestamp
|
||||
|
||||
function RDB_Bootstrap.getBootTimestamp()
|
||||
return bootTimestamp
|
||||
end
|
||||
|
||||
local function runSelfTests()
|
||||
if not RDB_Constants.DEBUG then
|
||||
if not RDB_Config.get("DebugSelfTest") then
|
||||
return
|
||||
end
|
||||
|
||||
@@ -35,11 +49,12 @@ end
|
||||
|
||||
local function registerBaseOptions()
|
||||
local OPT = RDB_Constants.OPT
|
||||
RDB_OptionsRegistry.register(OPT.PROTOCOL_VERSION, "{}", RDB_Constants.OPTION_MAX_LENGTH)
|
||||
RDB_OptionsRegistry.register(OPT.WORLD_STATS, "{}", RDB_Constants.OPTION_MAX_LENGTH)
|
||||
RDB_OptionsRegistry.register(OPT.REQUEST, "{}", RDB_Constants.OPTION_MAX_LENGTH)
|
||||
RDB_OptionsRegistry.register(OPT.RESPONSE, "{}", RDB_Constants.OPTION_MAX_LENGTH)
|
||||
RDB_OptionsRegistry.register(OPT.LAST_RESPONSE, "0", RDB_Constants.OPTION_MAX_LENGTH)
|
||||
local optionMaxLength = RDB_Config.get("OptionMaxLength")
|
||||
RDB_OptionsRegistry.register(OPT.PROTOCOL_VERSION, "{}", optionMaxLength)
|
||||
RDB_OptionsRegistry.register(OPT.WORLD_STATS, "{}", optionMaxLength)
|
||||
RDB_OptionsRegistry.register(OPT.REQUEST, "{}", optionMaxLength)
|
||||
RDB_OptionsRegistry.register(OPT.RESPONSE, "{}", optionMaxLength)
|
||||
RDB_OptionsRegistry.register(OPT.LAST_RESPONSE, "0", optionMaxLength)
|
||||
end
|
||||
|
||||
local function registerOps()
|
||||
@@ -47,20 +62,33 @@ local function registerOps()
|
||||
RDB_OpPlayerGet.register()
|
||||
RDB_OpPlayerList.register()
|
||||
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_Constants.PROTOCOL_VERSION,
|
||||
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)
|
||||
end
|
||||
|
||||
local function onServerStarted()
|
||||
if not bootTimestamp then
|
||||
bootTimestamp = getTimestampMs()
|
||||
end
|
||||
runSelfTests()
|
||||
RDB_Config.init()
|
||||
registerBaseOptions()
|
||||
registerOps()
|
||||
publishProtocolVersion()
|
||||
|
||||
+37
-31
@@ -1,45 +1,51 @@
|
||||
---@diagnostic disable: need-check-nil
|
||||
|
||||
-- ModData-backed bridge configuration: rate limits, payload cap, sensitive
|
||||
-- field policy. Defaults are baked in and only written to the ModData table
|
||||
-- the first time it's created.
|
||||
-- Facade over ALL scalar constants/settings -- the single point of access,
|
||||
-- so no other file should index RDB_Constants directly for a scalar value.
|
||||
-- Sandbox-tunable values (rate limits, poll cadence, idempotency TTL, debug
|
||||
-- self-tests) live in
|
||||
-- Contents/mods/RconDataBridge/common/media/sandbox-options.txt and are read
|
||||
-- live from SandboxVars.RconDataBridge.*. Anything NOT sandbox-tunable (e.g.
|
||||
-- MaxPayloadBytes/OptionMaxLength, sized against the fixed TextServerOption
|
||||
-- capacity -- base64 expansion of the payload must still fit, so an
|
||||
-- admin-set value with no matching engine-side capacity change could
|
||||
-- silently truncate a request ServerOptions can't hold; or ProtocolVersion/
|
||||
-- PlayerStatsPrefix, protocol identifiers, not settings) instead falls back
|
||||
-- to a same-named RDB_Constants field. Adding either kind of value never
|
||||
-- needs a new branch here -- just a sandbox-options.txt entry or a
|
||||
-- RDB_Constants field. (Unit conversions, like IdempotencyTtlSeconds ->
|
||||
-- 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 = {}
|
||||
|
||||
local TAG = "RconDataBridge_Config"
|
||||
|
||||
local DEFAULTS = {
|
||||
maxPayloadBytes = RDB_Constants.MAX_PAYLOAD_BYTES,
|
||||
rateLimitMaxRequests = 10,
|
||||
rateLimitWindowSeconds = 10,
|
||||
includeSensitiveFields = false,
|
||||
}
|
||||
|
||||
local store
|
||||
|
||||
function RDB_Config.init()
|
||||
store = ModData.getOrCreate(TAG)
|
||||
for key, value in pairs(DEFAULTS) do
|
||||
if store[key] == nil then
|
||||
store[key] = value
|
||||
end
|
||||
end
|
||||
-- PascalCase (sandbox-var convention, e.g. "MaxPayloadBytes") ->
|
||||
-- SCREAMING_SNAKE_CASE (RDB_Constants convention, "MAX_PAYLOAD_BYTES").
|
||||
local function toConstantKey(key)
|
||||
return (key:gsub("(%l)(%u)", "%1_%2")):upper()
|
||||
end
|
||||
|
||||
function RDB_Config.get(key)
|
||||
if not store then
|
||||
RDB_Config.init()
|
||||
local v = SandboxVars.RconDataBridge[key]
|
||||
if v ~= nil then
|
||||
return v
|
||||
end
|
||||
|
||||
return store[key]
|
||||
return RDB_Constants[toConstantKey(key)]
|
||||
end
|
||||
|
||||
function RDB_Config.set(key, value)
|
||||
if not store then
|
||||
RDB_Config.init()
|
||||
end
|
||||
|
||||
store[key] = value
|
||||
function RDB_Config.getAll()
|
||||
return {
|
||||
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
|
||||
+33
-9
@@ -2,15 +2,16 @@
|
||||
-- the original response instead of re-executing the op.
|
||||
-- Persisted via ModData so it survives restarts.
|
||||
--
|
||||
-- Entries expire after RDB_Constants.IDEMPOTENCY_TTL_MS (60s by default):
|
||||
-- a request id is only idempotent for retries within that window, not
|
||||
-- forever. Without a TTL, a client that reuses a fixed id for routine
|
||||
-- polling would get the first-ever response back on every call, since a
|
||||
-- low-traffic server would rarely reach MAX_ENTRIES and trigger the
|
||||
-- count-based eviction below.
|
||||
-- Entries expire after RDB_Config.get("IdempotencyTtlSeconds") (60s by
|
||||
-- default, admin-tunable via sandbox-options.txt): a request id is only
|
||||
-- idempotent for retries within that window, not forever. Without a TTL, a
|
||||
-- client that reuses a fixed id for routine polling would get the
|
||||
-- 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_Log")
|
||||
require("RconDataBridge/RDB_Constants")
|
||||
require("RconDataBridge/RDB_Config")
|
||||
require("RconDataBridge/RDB_Log")
|
||||
|
||||
RDB_Idempotency = {}
|
||||
|
||||
@@ -27,7 +28,8 @@ local function ensureStore()
|
||||
end
|
||||
|
||||
local function isExpired(entry)
|
||||
return getTimestampMs() - (entry.ts or 0) >= RDB_Constants.IDEMPOTENCY_TTL_MS
|
||||
local ttlMs = RDB_Config.get("IdempotencyTtlSeconds") * 1000
|
||||
return getTimestampMs() - (entry.ts or 0) >= ttlMs
|
||||
end
|
||||
|
||||
function RDB_Idempotency.has(id)
|
||||
@@ -82,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
|
||||
+45
-3
@@ -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
|
||||
|
||||
|
||||
+2
-2
@@ -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 = {}
|
||||
|
||||
|
||||
+16
-10
@@ -6,14 +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_Constants")
|
||||
require("RconDataBridge/RDB_Log")
|
||||
require("RconDataBridge/RDB_Json")
|
||||
require("RconDataBridge/RDB_OptionsRegistry")
|
||||
require("RconDataBridge/RDB_Config")
|
||||
|
||||
RDB_PlayerSnapshot = {}
|
||||
|
||||
@@ -78,8 +81,8 @@ function RDB_PlayerSnapshot.publishStatsOption(id)
|
||||
return
|
||||
end
|
||||
|
||||
local optionName = RDB_Constants.PLAYER_STATS_PREFIX .. id:gsub("[^%w_]", "_")
|
||||
RDB_OptionsRegistry.register(optionName, "{}", RDB_Constants.OPTION_MAX_LENGTH)
|
||||
local optionName = RDB_Config.get("PlayerStatsPrefix") .. id:gsub("[^%w_]", "_")
|
||||
RDB_OptionsRegistry.register(optionName, "{}", RDB_Config.get("OptionMaxLength"))
|
||||
RDB_OptionsRegistry.set(optionName, RDB_Json.encode(snapshot))
|
||||
end
|
||||
|
||||
@@ -133,7 +136,7 @@ local initialized = false
|
||||
|
||||
local function onTick()
|
||||
tickCounter = tickCounter + 1
|
||||
if tickCounter < RDB_Constants.POLL_EVERY_TICKS then
|
||||
if tickCounter < RDB_Config.get("RosterPollTicks") then
|
||||
return
|
||||
end
|
||||
|
||||
@@ -144,6 +147,8 @@ local function onTick()
|
||||
end
|
||||
end
|
||||
|
||||
-- Registered on BOTH OnTick and OnTickEvenPaused, same as
|
||||
-- RDB_RequestPipeline.
|
||||
function RDB_PlayerSnapshot.init()
|
||||
if initialized then
|
||||
return
|
||||
@@ -151,5 +156,6 @@ function RDB_PlayerSnapshot.init()
|
||||
initialized = true
|
||||
|
||||
Events.OnTick.Add(onTick)
|
||||
Events.OnTickEvenPaused.Add(onTick)
|
||||
Events.OnCharacterDeath.Add(RDB_PlayerSnapshot.onCharacterDeath)
|
||||
end
|
||||
+246
-67
@@ -1,25 +1,38 @@
|
||||
-- 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_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 {
|
||||
v = RDB_Constants.PROTOCOL_VERSION,
|
||||
v = RDB_Config.get("ProtocolVersion"),
|
||||
id = id,
|
||||
ok = true,
|
||||
data = data or {}
|
||||
@@ -28,62 +41,60 @@ end
|
||||
|
||||
local function buildErrorResponse(id, code, message)
|
||||
return {
|
||||
v = RDB_Constants.PROTOCOL_VERSION,
|
||||
v = RDB_Config.get("ProtocolVersion"),
|
||||
id = id,
|
||||
ok = false,
|
||||
error = { code = code, message = 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
|
||||
|
||||
-- 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
|
||||
-- If an op handler throws (a bug, a bad deploy, a version mismatch between
|
||||
-- files), surface it as a fast INTERNAL_ERROR response instead of silently
|
||||
-- swallowing it. The raw Lua error is logged server-side only, never
|
||||
-- sent to the client.
|
||||
local function safeDispatch(op, args)
|
||||
local ok, a, b, c = pcall(RDB_OpRegistry.dispatch, op, args)
|
||||
if not ok then
|
||||
RDB_Log.error("op '" .. tostring(op) .. "' handler threw: " .. tostring(a))
|
||||
return false, RDB_Constants.ERROR_CODES.INTERNAL_ERROR, "Unhandled error in operation handler."
|
||||
end
|
||||
return a, b, c
|
||||
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 function extractId(decoded)
|
||||
return (type(decoded) == "table" and type(decoded.id) == "string") and decoded.id or ""
|
||||
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
|
||||
|
||||
@@ -91,20 +102,23 @@ local function processRequest(rawBase64)
|
||||
|
||||
if RDB_Idempotency.has(id) then
|
||||
local cached = RDB_Idempotency.get(id)
|
||||
publishResponse(cached)
|
||||
audit(id, op, cached.ok, cached.ok and nil or (cached.error and cached.error.code))
|
||||
local cachedErrCode = nil
|
||||
if not cached.ok then
|
||||
cachedErrCode = cached.error and cached.error.code
|
||||
end
|
||||
audit(id, op, cached.ok, cachedErrCode)
|
||||
return
|
||||
end
|
||||
|
||||
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
|
||||
|
||||
local dispatchOk, dataOrCode, message = RDB_OpRegistry.dispatch(op, args)
|
||||
local dispatchOk, dataOrCode, message = safeDispatch(op, args)
|
||||
local response
|
||||
if dispatchOk then
|
||||
response = buildOkResponse(id, dataOrCode)
|
||||
@@ -113,39 +127,204 @@ local function processRequest(rawBase64)
|
||||
end
|
||||
|
||||
RDB_Idempotency.put(id, response)
|
||||
publishResponse(response)
|
||||
audit(id, op, dispatchOk, dispatchOk and nil or dataOrCode)
|
||||
|
||||
local errCode = nil
|
||||
if not dispatchOk then
|
||||
errCode = dataOrCode
|
||||
end
|
||||
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_Constants.POLL_EVERY_TICKS 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
|
||||
|
||||
-- Guarded: Events.OnServerStarted fires more than once per boot (see
|
||||
-- RESEARCH_LOG.md), and Events.OnTick.Add does not deduplicate identical
|
||||
-- listeners, so calling this twice would otherwise double-register onTick.
|
||||
-- Guarded: Events.OnServerStarted fires more than once per boot,
|
||||
-- and Events.OnTick.Add does not deduplicate identical listeners,
|
||||
-- so calling this twice would otherwise double-register onTick.
|
||||
--
|
||||
-- Registered on BOTH OnTick and OnTickEvenPaused: decompiling GameWindow's
|
||||
-- main loop shows these two are mutually exclusive per real engine tick;
|
||||
-- normal ticks fire OnTick (via IngameState's update path), while a tick
|
||||
-- where the server is paused (PauseEmpty=true and no players connected;
|
||||
-- see zombie.GameTime.isGamePaused) fires OnTickEvenPaused instead, never
|
||||
-- both. Without the second registration, the entire bridge (every op, not
|
||||
-- just one) goes completely inert on any server running PauseEmpty=true
|
||||
-- whenever it's empty: no event ever calls onTick, so a request just sits
|
||||
-- in RconDataBridge_Request forever with no response and no error, and a
|
||||
-- client sees a silent timeout with nothing to diagnose.
|
||||
function RDB_RequestPipeline.init()
|
||||
if initialized then
|
||||
return
|
||||
end
|
||||
|
||||
initialized = true
|
||||
lastSeenRaw = RDB_OptionsRegistry.get(RDB_Constants.OPT.REQUEST)
|
||||
|
||||
Events.OnTick.Add(onTick)
|
||||
Events.OnTickEvenPaused.Add(onTick)
|
||||
end
|
||||
+63
@@ -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
|
||||
+25
-9
@@ -5,13 +5,13 @@
|
||||
-- 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 = {}
|
||||
|
||||
function RDB_Security.checkPayloadSize(raw)
|
||||
if #raw > RDB_Config.get("maxPayloadBytes") then
|
||||
if #raw > RDB_Config.get("MaxPayloadBytes") then
|
||||
return false, RDB_Constants.ERROR_CODES.PAYLOAD_TOO_LARGE, "Request payload exceeds size limit"
|
||||
end
|
||||
|
||||
@@ -24,7 +24,7 @@ function RDB_Security.validateEnvelope(obj)
|
||||
if type(obj) ~= "table" then
|
||||
return false, RDB_Constants.ERROR_CODES.SCHEMA_ERROR, "Request must be a JSON object"
|
||||
end
|
||||
if obj.v ~= RDB_Constants.PROTOCOL_VERSION then
|
||||
if obj.v ~= RDB_Config.get("ProtocolVersion") then
|
||||
return false, RDB_Constants.ERROR_CODES.SCHEMA_ERROR, "Unsupported or missing protocol version"
|
||||
end
|
||||
if type(obj.id) ~= "string" or #obj.id == 0 or #obj.id > 128 then
|
||||
@@ -41,10 +41,12 @@ end
|
||||
|
||||
local requestTimestamps = {}
|
||||
|
||||
function RDB_Security.checkRateLimit()
|
||||
-- Drops timestamps that have aged out of the current window and returns how
|
||||
-- many remain. Shared by checkRateLimit (which then appends the new request)
|
||||
-- and getRateLimitStatus (which only observes).
|
||||
local function pruneAndCount()
|
||||
local now = getTimestampMs()
|
||||
local windowMs = RDB_Config.get("rateLimitWindowSeconds") * 1000
|
||||
local maxRequests = RDB_Config.get("rateLimitMaxRequests")
|
||||
local windowMs = RDB_Config.get("RateLimitWindowSeconds") * 1000
|
||||
|
||||
local kept = {}
|
||||
for _, ts in ipairs(requestTimestamps) do
|
||||
@@ -54,10 +56,24 @@ function RDB_Security.checkRateLimit()
|
||||
end
|
||||
requestTimestamps = kept
|
||||
|
||||
if #requestTimestamps >= maxRequests then
|
||||
return #requestTimestamps
|
||||
end
|
||||
|
||||
function RDB_Security.checkRateLimit()
|
||||
local maxRequests = RDB_Config.get("RateLimitMaxRequests")
|
||||
|
||||
if pruneAndCount() >= maxRequests then
|
||||
return false, RDB_Constants.ERROR_CODES.RATE_LIMITED, "Too many requests, slow down"
|
||||
end
|
||||
|
||||
requestTimestamps[#requestTimestamps + 1] = now
|
||||
requestTimestamps[#requestTimestamps + 1] = getTimestampMs()
|
||||
return true
|
||||
end
|
||||
|
||||
function RDB_Security.getRateLimitStatus()
|
||||
return {
|
||||
currentWindowRequests = pruneAndCount(),
|
||||
maxRequests = RDB_Config.get("RateLimitMaxRequests"),
|
||||
windowSeconds = RDB_Config.get("RateLimitWindowSeconds"),
|
||||
}
|
||||
end
|
||||
+5
-5
@@ -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 = {}
|
||||
|
||||
@@ -28,7 +28,7 @@ local function refresh()
|
||||
minute = gt:getMinutes(),
|
||||
},
|
||||
isNight = gt:isNight(),
|
||||
isRaining = gt:isRainingToday(),
|
||||
isRaining = RainManager.isRaining(), -- GameTime:isRainingToday() is a dead stub in B42.20
|
||||
timeMultiplier = gt:getMultiplier(),
|
||||
generatedAt = getTimestampMs(),
|
||||
}
|
||||
|
||||
+3
-13
@@ -6,9 +6,7 @@
|
||||
|
||||
RDB_Constants = {}
|
||||
|
||||
RDB_Constants.DEBUG = true
|
||||
|
||||
RDB_Constants.PROTOCOL_VERSION = 1
|
||||
RDB_Constants.PROTOCOL_VERSION = 2
|
||||
|
||||
RDB_Constants.OPT = {
|
||||
PROTOCOL_VERSION = "RconDataBridge_ProtocolVersion",
|
||||
@@ -22,16 +20,6 @@ RDB_Constants.PLAYER_STATS_PREFIX = "RconDataBridge_PlayerStats_"
|
||||
|
||||
RDB_Constants.MAX_PAYLOAD_BYTES = 4096
|
||||
RDB_Constants.OPTION_MAX_LENGTH = 8192
|
||||
RDB_Constants.POLL_EVERY_TICKS = 30
|
||||
|
||||
-- How long a request id's cached response is replayed for on retry before
|
||||
-- it's treated as expired and the op runs again. Deliberately short: a
|
||||
-- client that reuses a fixed id for routine polling (e.g. "ws-poll" every
|
||||
-- few minutes) should get a fresh answer each time, not the first-ever
|
||||
-- response forever. A count-based cap alone (MAX_ENTRIES in
|
||||
-- RDB_Idempotency) doesn't help here, it only evicts under high request
|
||||
-- volume, never under low-and-slow polling, which is exactly this case.
|
||||
RDB_Constants.IDEMPOTENCY_TTL_MS = 60 * 1000
|
||||
|
||||
RDB_Constants.ERROR_CODES = {
|
||||
SCHEMA_ERROR = "SCHEMA_ERROR",
|
||||
@@ -41,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",
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"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_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",
|
||||
"Sandbox_RconDataBridge_RateLimitMaxRequests_tooltip": "Maximum RCON Data Bridge requests allowed per rate-limit window.",
|
||||
"Sandbox_RconDataBridge_RateLimitWindowSeconds": "Rate Limit: Window (seconds)",
|
||||
"Sandbox_RconDataBridge_RateLimitWindowSeconds_tooltip": "Length of the rolling rate-limit window, in seconds."
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
VERSION = 1,
|
||||
|
||||
option RconDataBridge.DebugSelfTest
|
||||
{
|
||||
type = boolean,
|
||||
default = true,
|
||||
page = RconDataBridge,
|
||||
translation = RconDataBridge_DebugSelfTest,
|
||||
}
|
||||
|
||||
option RconDataBridge.RosterPollTicks
|
||||
{
|
||||
type = integer,
|
||||
min = 1,
|
||||
max = 300,
|
||||
default = 30,
|
||||
page = RconDataBridge,
|
||||
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
|
||||
{
|
||||
type = integer,
|
||||
min = 1,
|
||||
max = 3600,
|
||||
default = 60,
|
||||
page = RconDataBridge,
|
||||
translation = RconDataBridge_IdempotencyTtlSeconds,
|
||||
}
|
||||
|
||||
option RconDataBridge.RateLimitMaxRequests
|
||||
{
|
||||
type = integer,
|
||||
min = 1,
|
||||
max = 1000,
|
||||
default = 10,
|
||||
page = RconDataBridge,
|
||||
translation = RconDataBridge_RateLimitMaxRequests,
|
||||
}
|
||||
|
||||
option RconDataBridge.RateLimitWindowSeconds
|
||||
{
|
||||
type = integer,
|
||||
min = 1,
|
||||
max = 3600,
|
||||
default = 10,
|
||||
page = RconDataBridge,
|
||||
translation = RconDataBridge_RateLimitWindowSeconds,
|
||||
}
|
||||
Reference in new issue
Block a user