Archived
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dce67aae3e | ||
|
|
3f4a70ebfe | ||
|
|
9ed40d7017 | ||
|
|
30f5faa9a7 | ||
|
|
726bbe8064 | ||
|
|
68aba1bd47 | ||
|
|
5de8493cef |
No files matched your search
+2
-1
@@ -1,7 +1,8 @@
|
|||||||
.idea
|
.idea
|
||||||
|
|
||||||
pzlibs
|
lib
|
||||||
.emmyrc.json
|
.emmyrc.json
|
||||||
|
.*/
|
||||||
|
|
||||||
scripts
|
scripts
|
||||||
*.md
|
*.md
|
||||||
|
|||||||
+1
@@ -12,6 +12,7 @@ local MAX_LIMIT = 200
|
|||||||
|
|
||||||
function RDB_OpAuditLogGet.register()
|
function RDB_OpAuditLogGet.register()
|
||||||
RDB_OpRegistry.register("get_audit_log", {
|
RDB_OpRegistry.register("get_audit_log", {
|
||||||
|
core = true,
|
||||||
handler = function(args)
|
handler = function(args)
|
||||||
local limit = DEFAULT_LIMIT
|
local limit = DEFAULT_LIMIT
|
||||||
if type(args.limit) == "number" then
|
if type(args.limit) == "number" then
|
||||||
|
|||||||
+1
@@ -15,6 +15,7 @@ end
|
|||||||
|
|
||||||
function RDB_OpBridgeStatus.register()
|
function RDB_OpBridgeStatus.register()
|
||||||
RDB_OpRegistry.register("get_bridge_status", {
|
RDB_OpRegistry.register("get_bridge_status", {
|
||||||
|
core = true,
|
||||||
handler = function(_)
|
handler = function(_)
|
||||||
local bootedAt = RDB_Bootstrap.getBootTimestamp()
|
local bootedAt = RDB_Bootstrap.getBootTimestamp()
|
||||||
local now = getTimestampMs()
|
local now = getTimestampMs()
|
||||||
|
|||||||
+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()
|
function RDB_OpPlayerGet.register()
|
||||||
RDB_OpRegistry.register("get_player", {
|
RDB_OpRegistry.register("get_player", {
|
||||||
|
core = true,
|
||||||
argsSchema = { id = "string" },
|
argsSchema = { id = "string" },
|
||||||
handler = function(args)
|
handler = function(args)
|
||||||
local snapshot = RDB_PlayerSnapshot.get(args.id)
|
local snapshot = RDB_PlayerSnapshot.get(args.id)
|
||||||
|
|||||||
+1
@@ -12,6 +12,7 @@ local MAX_LIMIT = 200
|
|||||||
|
|
||||||
function RDB_OpPlayerList.register()
|
function RDB_OpPlayerList.register()
|
||||||
RDB_OpRegistry.register("list_players", {
|
RDB_OpRegistry.register("list_players", {
|
||||||
|
core = true,
|
||||||
handler = function(args)
|
handler = function(args)
|
||||||
local all = RDB_PlayerSnapshot.listAll()
|
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()
|
function RDB_OpServerSave.register()
|
||||||
RDB_OpRegistry.register("save_server", {
|
RDB_OpRegistry.register("save_server", {
|
||||||
|
core = true,
|
||||||
handler = function(_)
|
handler = function(_)
|
||||||
local ok = pcall(function() GameWindow.save(true) end)
|
local ok = pcall(function() GameWindow.save(true) end)
|
||||||
if not ok then
|
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()
|
function RDB_OpWorldGetStats.register()
|
||||||
RDB_OpRegistry.register("get_world_stats", {
|
RDB_OpRegistry.register("get_world_stats", {
|
||||||
|
core = true,
|
||||||
handler = function(_)
|
handler = function(_)
|
||||||
return true, RDB_WorldStats.collect()
|
return true, RDB_WorldStats.collect()
|
||||||
end,
|
end,
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
-- (bad payload, unknown op, rate-limited, etc). Persisted as a bounded
|
-- (bad payload, unknown op, rate-limited, etc). Persisted as a bounded
|
||||||
-- ring buffer via ModData, plus a console line for live tailing.
|
-- ring buffer via ModData, plus a console line for live tailing.
|
||||||
|
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
|
|
||||||
RDB_AuditLog = {}
|
RDB_AuditLog = {}
|
||||||
|
|
||||||
|
|||||||
+30
-16
@@ -1,19 +1,23 @@
|
|||||||
require("RconDataBridge.RDB_Constants")
|
require("RconDataBridge/RDB_Constants")
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
require("RconDataBridge.RDB_Json")
|
require("RconDataBridge/RDB_Json")
|
||||||
require("RconDataBridge.RDB_Base64")
|
require("RconDataBridge/RDB_Base64")
|
||||||
require("RconDataBridge.RDB_OptionsRegistry")
|
require("RconDataBridge/RDB_OptionsRegistry")
|
||||||
require("RconDataBridge.RDB_Config")
|
require("RconDataBridge/RDB_Config")
|
||||||
require("RconDataBridge.RDB_OpRegistry")
|
require("RconDataBridge/RDB_OpRegistry")
|
||||||
require("RconDataBridge.RDB_RequestPipeline")
|
require("RconDataBridge/RDB_RequestQueue")
|
||||||
require("RconDataBridge.RDB_WorldStats")
|
require("RconDataBridge/RDB_RequestPipeline")
|
||||||
require("RconDataBridge.RDB_PlayerSnapshot")
|
require("RconDataBridge/RDB_WorldStats")
|
||||||
require("RconDataBridge.Ops.RDB_OpWorldGetStats")
|
require("RconDataBridge/RDB_PlayerSnapshot")
|
||||||
require("RconDataBridge.Ops.RDB_OpPlayerGet")
|
require("RconDataBridge/Ops/RDB_OpWorldGetStats")
|
||||||
require("RconDataBridge.Ops.RDB_OpPlayerList")
|
require("RconDataBridge/Ops/RDB_OpPlayerGet")
|
||||||
require("RconDataBridge.Ops.RDB_OpServerSave")
|
require("RconDataBridge/Ops/RDB_OpPlayerList")
|
||||||
require("RconDataBridge.Ops.RDB_OpBridgeStatus")
|
require("RconDataBridge/Ops/RDB_OpServerSave")
|
||||||
require("RconDataBridge.Ops.RDB_OpAuditLogGet")
|
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 = {}
|
RDB_Bootstrap = {}
|
||||||
|
|
||||||
@@ -60,12 +64,21 @@ local function registerOps()
|
|||||||
RDB_OpServerSave.register()
|
RDB_OpServerSave.register()
|
||||||
RDB_OpBridgeStatus.register()
|
RDB_OpBridgeStatus.register()
|
||||||
RDB_OpAuditLogGet.register()
|
RDB_OpAuditLogGet.register()
|
||||||
|
RDB_OpListOps.register()
|
||||||
|
RDB_OpSetOpEnabled.register()
|
||||||
|
RDB_OpQueueStatus.register()
|
||||||
end
|
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 function publishProtocolVersion()
|
||||||
local json = RDB_Json.encode({
|
local json = RDB_Json.encode({
|
||||||
version = RDB_Config.get("ProtocolVersion"),
|
version = RDB_Config.get("ProtocolVersion"),
|
||||||
ops = RDB_OpRegistry.listNames(),
|
ops = RDB_OpRegistry.listNames(),
|
||||||
|
queueing = {
|
||||||
|
maxQueueDepth = RDB_Config.get("MaxQueueDepth"),
|
||||||
|
requestsPerTick = RDB_Config.get("RequestsPerTick"),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
RDB_OptionsRegistry.set(RDB_Constants.OPT.PROTOCOL_VERSION, json)
|
RDB_OptionsRegistry.set(RDB_Constants.OPT.PROTOCOL_VERSION, json)
|
||||||
@@ -79,6 +92,7 @@ local function onServerStarted()
|
|||||||
registerBaseOptions()
|
registerBaseOptions()
|
||||||
registerOps()
|
registerOps()
|
||||||
publishProtocolVersion()
|
publishProtocolVersion()
|
||||||
|
RDB_OpRegistry.setChangeListener(publishProtocolVersion)
|
||||||
RDB_RequestPipeline.init()
|
RDB_RequestPipeline.init()
|
||||||
RDB_WorldStats.init()
|
RDB_WorldStats.init()
|
||||||
RDB_PlayerSnapshot.init()
|
RDB_PlayerSnapshot.init()
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
-- milliseconds, belong in the one caller that needs the converted unit, not
|
-- milliseconds, belong in the one caller that needs the converted unit, not
|
||||||
-- here -- see RDB_Idempotency.)
|
-- here -- see RDB_Idempotency.)
|
||||||
|
|
||||||
require("RconDataBridge.RDB_Constants")
|
require("RconDataBridge/RDB_Constants")
|
||||||
|
|
||||||
RDB_Config = {}
|
RDB_Config = {}
|
||||||
|
|
||||||
@@ -41,5 +41,11 @@ function RDB_Config.getAll()
|
|||||||
maxPayloadBytes = RDB_Config.get("MaxPayloadBytes"),
|
maxPayloadBytes = RDB_Config.get("MaxPayloadBytes"),
|
||||||
rateLimitMaxRequests = RDB_Config.get("RateLimitMaxRequests"),
|
rateLimitMaxRequests = RDB_Config.get("RateLimitMaxRequests"),
|
||||||
rateLimitWindowSeconds = RDB_Config.get("RateLimitWindowSeconds"),
|
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
|
end
|
||||||
+25
-3
@@ -9,9 +9,9 @@
|
|||||||
-- first-ever response back on every call, since a low-traffic server would
|
-- first-ever response back on every call, since a low-traffic server would
|
||||||
-- rarely reach MAX_ENTRIES and trigger the count-based eviction below.
|
-- rarely reach MAX_ENTRIES and trigger the count-based eviction below.
|
||||||
|
|
||||||
require("RconDataBridge.RDB_Constants")
|
require("RconDataBridge/RDB_Constants")
|
||||||
require("RconDataBridge.RDB_Config")
|
require("RconDataBridge/RDB_Config")
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
|
|
||||||
RDB_Idempotency = {}
|
RDB_Idempotency = {}
|
||||||
|
|
||||||
@@ -84,3 +84,25 @@ function RDB_Idempotency.put(id, response)
|
|||||||
s[id] = { response = response, ts = getTimestampMs() }
|
s[id] = { response = response, ts = getTimestampMs() }
|
||||||
prune(s)
|
prune(s)
|
||||||
end
|
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
|
||||||
+60
-3
@@ -1,22 +1,68 @@
|
|||||||
-- Table-driven op registry. This is the allowlist: dispatch only ever looks
|
-- 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
|
-- 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.
|
-- 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 = {}
|
RDB_OpRegistry = {}
|
||||||
|
|
||||||
local handlers = {}
|
local handlers = {}
|
||||||
|
local changeListener
|
||||||
|
|
||||||
-- def: { handler = function(args) -> ok, dataOrErrCode[, errMessage], argsSchema = {fieldName = "type", ...} }
|
-- Set once by RDB_Bootstrap so RconDataBridge_ProtocolVersion's `ops` list
|
||||||
|
-- stays current when a plugin mod registers after bootstrap has run.
|
||||||
|
function RDB_OpRegistry.setChangeListener(fn)
|
||||||
|
changeListener = fn
|
||||||
|
end
|
||||||
|
|
||||||
|
local function notifyChanged()
|
||||||
|
if changeListener then
|
||||||
|
changeListener()
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 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)
|
function RDB_OpRegistry.register(name, def)
|
||||||
|
if def.enabled == nil then
|
||||||
|
def.enabled = true
|
||||||
|
end
|
||||||
handlers[name] = def
|
handlers[name] = def
|
||||||
|
notifyChanged()
|
||||||
|
end
|
||||||
|
|
||||||
|
function RDB_OpRegistry.unregister(name)
|
||||||
|
handlers[name] = nil
|
||||||
|
notifyChanged()
|
||||||
end
|
end
|
||||||
|
|
||||||
function RDB_OpRegistry.isRegistered(name)
|
function RDB_OpRegistry.isRegistered(name)
|
||||||
return handlers[name] ~= nil
|
return handlers[name] ~= nil
|
||||||
end
|
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()
|
function RDB_OpRegistry.listNames()
|
||||||
local names = {}
|
local names = {}
|
||||||
for name in pairs(handlers) do
|
for name in pairs(handlers) do
|
||||||
@@ -26,13 +72,24 @@ function RDB_OpRegistry.listNames()
|
|||||||
return names
|
return names
|
||||||
end
|
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 +
|
-- Validates args against the op's declared schema (shallow: field presence +
|
||||||
-- Lua type of top-level fields), then dispatches. Returns:
|
-- Lua type of top-level fields), then dispatches. Returns:
|
||||||
-- ok, data on success
|
-- ok, data on success
|
||||||
-- false, errCode, errMessage on failure (schema or handler-reported error)
|
-- false, errCode, errMessage on failure (schema or handler-reported error)
|
||||||
function RDB_OpRegistry.dispatch(name, args)
|
function RDB_OpRegistry.dispatch(name, args)
|
||||||
local def = handlers[name]
|
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)
|
return false, RDB_Constants.ERROR_CODES.OP_NOT_ALLOWED, "Unknown or disallowed operation: " .. tostring(name)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -25,8 +25,8 @@
|
|||||||
-- the request pipeline diffs the raw stored string for change detection
|
-- the request pipeline diffs the raw stored string for change detection
|
||||||
-- and needs to see it either way, decode failure included.
|
-- and needs to see it either way, decode failure included.
|
||||||
|
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
require("RconDataBridge.RDB_Base64")
|
require("RconDataBridge/RDB_Base64")
|
||||||
|
|
||||||
RDB_OptionsRegistry = {}
|
RDB_OptionsRegistry = {}
|
||||||
|
|
||||||
|
|||||||
+11
-9
@@ -6,15 +6,17 @@
|
|||||||
-- of truth for offline players..
|
-- of truth for offline players..
|
||||||
--
|
--
|
||||||
-- Connect/disconnect detection: no server-side connect/disconnect event was
|
-- Connect/disconnect detection: no server-side connect/disconnect event was
|
||||||
-- found in the stub trees, so this polls getOnlinePlayers() on the same
|
-- found in the stub trees, so this polls getOnlinePlayers() on its own
|
||||||
-- tick throttle as the request pipeline and diffs against the last-known
|
-- RosterPollTicks throttle (separate from RDB_RequestPipeline's adaptive
|
||||||
-- online set.
|
-- 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_Constants")
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
require("RconDataBridge.RDB_Json")
|
require("RconDataBridge/RDB_Json")
|
||||||
require("RconDataBridge.RDB_OptionsRegistry")
|
require("RconDataBridge/RDB_OptionsRegistry")
|
||||||
require("RconDataBridge.RDB_Config")
|
require("RconDataBridge/RDB_Config")
|
||||||
|
|
||||||
RDB_PlayerSnapshot = {}
|
RDB_PlayerSnapshot = {}
|
||||||
|
|
||||||
@@ -134,7 +136,7 @@ local initialized = false
|
|||||||
|
|
||||||
local function onTick()
|
local function onTick()
|
||||||
tickCounter = tickCounter + 1
|
tickCounter = tickCounter + 1
|
||||||
if tickCounter < RDB_Config.get("PollEveryTicks") then
|
if tickCounter < RDB_Config.get("RosterPollTicks") then
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
+202
-61
@@ -1,22 +1,34 @@
|
|||||||
-- Polls RconDataBridge_Request for changes (there is no "option changed"
|
-- Polls RconDataBridge_Request for changes (there is no "option changed"
|
||||||
-- event in the PZ Lua API) and runs the full request/response pipeline.
|
-- event in the PZ Lua API). A write is decoded as a JSON array of request
|
||||||
-- Every outcome, including every rejection, is audited.
|
-- 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_Constants")
|
||||||
require("RconDataBridge.RDB_Json")
|
require("RconDataBridge/RDB_Json")
|
||||||
require("RconDataBridge.RDB_Base64")
|
require("RconDataBridge/RDB_Base64")
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
require("RconDataBridge.RDB_OptionsRegistry")
|
require("RconDataBridge/RDB_OptionsRegistry")
|
||||||
require("RconDataBridge.RDB_Config")
|
require("RconDataBridge/RDB_Config")
|
||||||
require("RconDataBridge.RDB_Security")
|
require("RconDataBridge/RDB_Security")
|
||||||
require("RconDataBridge.RDB_Idempotency")
|
require("RconDataBridge/RDB_Idempotency")
|
||||||
require("RconDataBridge.RDB_AuditLog")
|
require("RconDataBridge/RDB_AuditLog")
|
||||||
require("RconDataBridge.RDB_OpRegistry")
|
require("RconDataBridge/RDB_OpRegistry")
|
||||||
|
require("RconDataBridge/RDB_RequestQueue")
|
||||||
|
|
||||||
RDB_RequestPipeline = {}
|
RDB_RequestPipeline = {}
|
||||||
|
|
||||||
local lastSeenRaw = nil
|
local lastSeenRaw = nil
|
||||||
local tickCounter = 0
|
local tickCounter = 0
|
||||||
|
local lastActivityAt = 0
|
||||||
|
|
||||||
local function buildOkResponse(id, data)
|
local function buildOkResponse(id, data)
|
||||||
return {
|
return {
|
||||||
@@ -36,11 +48,6 @@ local function buildErrorResponse(id, code, message)
|
|||||||
}
|
}
|
||||||
end
|
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)
|
local function audit(id, op, ok, code)
|
||||||
RDB_AuditLog.record({ id = id, op = op, ok = ok, code = code })
|
RDB_AuditLog.record({ id = id, op = op, ok = ok, code = code })
|
||||||
end
|
end
|
||||||
@@ -58,46 +65,36 @@ local function safeDispatch(op, args)
|
|||||||
return a, b, c
|
return a, b, c
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Handles one raw request string end to end. raw is base64: RCON's
|
local function extractId(decoded)
|
||||||
-- changeoption command strips every literal double-quote character from
|
return (type(decoded) == "table" and type(decoded.id) == "string") and decoded.id or ""
|
||||||
-- every argument (see RESEARCH_LOG.md), so a client can't send raw JSON --
|
end
|
||||||
-- 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 sizeOk, sizeCode, sizeMsg = RDB_Security.checkPayloadSize(raw)
|
-- A response with a real id is cached so it survives into future polls (see
|
||||||
if not sizeOk then
|
-- flushResponses below) -- an id-less response (top-level payload errors
|
||||||
local response = buildErrorResponse("", sizeCode, sizeMsg)
|
-- that never got far enough to decode an id) has nothing a client could
|
||||||
publishResponse(response)
|
-- correlate it against anyway, so it only ever rides along on this tick's
|
||||||
audit("", "", false, sizeCode)
|
-- publish, same as v1's single-mailbox behavior for that one case.
|
||||||
return
|
local function cacheOrTransient(response, transientBucket)
|
||||||
end
|
if response.id ~= "" then
|
||||||
|
RDB_Idempotency.put(response.id, response)
|
||||||
local decoded, decodeErr = RDB_Json.decode(raw)
|
else
|
||||||
if decodeErr then
|
transientBucket[#transientBucket + 1] = response
|
||||||
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
|
|
||||||
end
|
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)
|
local envelopeOk, envelopeCode, envelopeMsg = RDB_Security.validateEnvelope(decoded)
|
||||||
if not envelopeOk then
|
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)
|
local response = buildErrorResponse(id, envelopeCode, envelopeMsg)
|
||||||
publishResponse(response)
|
|
||||||
audit(id, (type(decoded) == "table" and decoded.op) or "", false, envelopeCode)
|
audit(id, (type(decoded) == "table" and decoded.op) or "", false, envelopeCode)
|
||||||
|
if id ~= "" then
|
||||||
|
RDB_Idempotency.put(id, response)
|
||||||
|
end
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -105,8 +102,6 @@ local function processRequest(rawBase64)
|
|||||||
|
|
||||||
if RDB_Idempotency.has(id) then
|
if RDB_Idempotency.has(id) then
|
||||||
local cached = RDB_Idempotency.get(id)
|
local cached = RDB_Idempotency.get(id)
|
||||||
publishResponse(cached)
|
|
||||||
|
|
||||||
local cachedErrCode = nil
|
local cachedErrCode = nil
|
||||||
if not cached.ok then
|
if not cached.ok then
|
||||||
cachedErrCode = cached.error and cached.error.code
|
cachedErrCode = cached.error and cached.error.code
|
||||||
@@ -118,8 +113,8 @@ local function processRequest(rawBase64)
|
|||||||
local rateOk, rateCode, rateMsg = RDB_Security.checkRateLimit()
|
local rateOk, rateCode, rateMsg = RDB_Security.checkRateLimit()
|
||||||
if not rateOk then
|
if not rateOk then
|
||||||
local response = buildErrorResponse(id, rateCode, rateMsg)
|
local response = buildErrorResponse(id, rateCode, rateMsg)
|
||||||
publishResponse(response)
|
|
||||||
audit(id, op, false, rateCode)
|
audit(id, op, false, rateCode)
|
||||||
|
RDB_Idempotency.put(id, response)
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -132,7 +127,6 @@ local function processRequest(rawBase64)
|
|||||||
end
|
end
|
||||||
|
|
||||||
RDB_Idempotency.put(id, response)
|
RDB_Idempotency.put(id, response)
|
||||||
publishResponse(response)
|
|
||||||
|
|
||||||
local errCode = nil
|
local errCode = nil
|
||||||
if not dispatchOk then
|
if not dispatchOk then
|
||||||
@@ -141,23 +135,170 @@ local function processRequest(rawBase64)
|
|||||||
audit(id, op, dispatchOk, errCode)
|
audit(id, op, dispatchOk, errCode)
|
||||||
end
|
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()
|
local function onTick()
|
||||||
tickCounter = tickCounter + 1
|
tickCounter = tickCounter + 1
|
||||||
if tickCounter < RDB_Config.get("PollEveryTicks") then
|
if tickCounter < currentIntervalTicks() then
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
tickCounter = 0
|
tickCounter = 0
|
||||||
|
|
||||||
|
local transientResponses = {}
|
||||||
|
local activity = false
|
||||||
|
|
||||||
local raw = RDB_OptionsRegistry.get(RDB_Constants.OPT.REQUEST)
|
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
|
return
|
||||||
end
|
end
|
||||||
lastSeenRaw = raw
|
|
||||||
|
|
||||||
local ok, err = pcall(processRequest, raw)
|
flushResponses(transientResponses)
|
||||||
if not ok then
|
|
||||||
RDB_Log.error("unhandled error processing request: " .. tostring(err))
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
local initialized = false
|
local initialized = false
|
||||||
|
|||||||
+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
|
||||||
+2
-2
@@ -5,8 +5,8 @@
|
|||||||
-- the same RconDataBridge_Request mailbox. The window is an in-memory sliding
|
-- the same RconDataBridge_Request mailbox. The window is an in-memory sliding
|
||||||
-- log; it does not need to survive a restart.
|
-- log; it does not need to survive a restart.
|
||||||
|
|
||||||
require("RconDataBridge.RDB_Constants")
|
require("RconDataBridge/RDB_Constants")
|
||||||
require("RconDataBridge.RDB_Config")
|
require("RconDataBridge/RDB_Config")
|
||||||
|
|
||||||
RDB_Security = {}
|
RDB_Security = {}
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
-- World telemetry, sourced from zombie.GameTime (getGameTime()).
|
-- World telemetry, sourced from zombie.GameTime (getGameTime()).
|
||||||
|
|
||||||
require("RconDataBridge.RDB_Constants")
|
require("RconDataBridge/RDB_Constants")
|
||||||
require("RconDataBridge.RDB_Log")
|
require("RconDataBridge/RDB_Log")
|
||||||
require("RconDataBridge.RDB_Json")
|
require("RconDataBridge/RDB_Json")
|
||||||
require("RconDataBridge.RDB_OptionsRegistry")
|
require("RconDataBridge/RDB_OptionsRegistry")
|
||||||
|
|
||||||
RDB_WorldStats = {}
|
RDB_WorldStats = {}
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
RDB_Constants = {}
|
RDB_Constants = {}
|
||||||
|
|
||||||
RDB_Constants.PROTOCOL_VERSION = 1
|
RDB_Constants.PROTOCOL_VERSION = 2
|
||||||
|
|
||||||
RDB_Constants.OPT = {
|
RDB_Constants.OPT = {
|
||||||
PROTOCOL_VERSION = "RconDataBridge_ProtocolVersion",
|
PROTOCOL_VERSION = "RconDataBridge_ProtocolVersion",
|
||||||
@@ -29,4 +29,6 @@ RDB_Constants.ERROR_CODES = {
|
|||||||
PLAYER_NOT_FOUND = "PLAYER_NOT_FOUND",
|
PLAYER_NOT_FOUND = "PLAYER_NOT_FOUND",
|
||||||
SAVE_FAILED = "SAVE_FAILED",
|
SAVE_FAILED = "SAVE_FAILED",
|
||||||
INTERNAL_ERROR = "INTERNAL_ERROR",
|
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": "RCON Data Bridge",
|
||||||
"Sandbox_RconDataBridge_DebugSelfTest": "Debug Self-Tests",
|
"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_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_RosterPollTicks": "Roster 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_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": "Idempotency Window (seconds)",
|
||||||
"Sandbox_RconDataBridge_IdempotencyTtlSeconds_tooltip": "How long a repeated request id replays its cached response instead of running again.",
|
"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": "Rate Limit: Max Requests",
|
||||||
|
|||||||
@@ -8,14 +8,64 @@ option RconDataBridge.DebugSelfTest
|
|||||||
translation = RconDataBridge_DebugSelfTest,
|
translation = RconDataBridge_DebugSelfTest,
|
||||||
}
|
}
|
||||||
|
|
||||||
option RconDataBridge.PollEveryTicks
|
option RconDataBridge.RosterPollTicks
|
||||||
{
|
{
|
||||||
type = integer,
|
type = integer,
|
||||||
min = 1,
|
min = 1,
|
||||||
max = 300,
|
max = 300,
|
||||||
default = 30,
|
default = 30,
|
||||||
page = RconDataBridge,
|
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
|
option RconDataBridge.IdempotencyTtlSeconds
|
||||||
|
|||||||
@@ -1,5 +1,119 @@
|
|||||||
# pz-rcon-data-bridge
|
# RCON Data Bridge
|
||||||
|
|
||||||
A Project Zomboid server mod that exposes structured world and player statistics through showoptions and accepts remote actions (limited function calls) through changeoptions/showoptions, enabling richer RCON tooling and automation.
|
A Project Zomboid (B42) server mod that turns the existing RCON connection into a small, allowlisted RPC surface. It adds no new port and no new authentication. Anything that can already run `changeoption` and `showoptions` can call it.
|
||||||
|
|
||||||
Mod for Project Zomboid B42.20
|
Out of the box it exposes world and player statistics and a few admin operations. This README is for mod developers who want to **register their own operations** so that RCON tools and bots can call into their mod.
|
||||||
|
|
||||||
|
## Adding your own op
|
||||||
|
|
||||||
|
An op is a named Lua function. External callers invoke it by name, pass a table of arguments, and get back either data or an error code.
|
||||||
|
|
||||||
|
### 1. Depend on this mod
|
||||||
|
|
||||||
|
In your mod's `mod.info`:
|
||||||
|
|
||||||
|
```
|
||||||
|
require=RconDataBridge
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Register from `Events.OnServerStarted`
|
||||||
|
|
||||||
|
Put this in a server-side Lua file, for example `media/lua/server/MyMod/MyMod_Ops.lua`:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local function onServerStarted()
|
||||||
|
RDB_OpRegistry.register("mymod_get_stash", {
|
||||||
|
argsSchema = { name = "string" },
|
||||||
|
handler = function(args)
|
||||||
|
local stash = MyMod.findStash(args.name)
|
||||||
|
if not stash then
|
||||||
|
return false, "STASH_NOT_FOUND", "No stash named " .. args.name
|
||||||
|
end
|
||||||
|
|
||||||
|
return true, { name = stash.name, items = stash.itemCount }
|
||||||
|
end,
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
Events.OnServerStarted.Add(onServerStarted)
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not register at file top level. Load order between mods is not guaranteed, so `RDB_OpRegistry` may not exist yet when your file first runs. `OnServerStarted` fires after every mod's files have loaded.
|
||||||
|
|
||||||
|
### The handler contract
|
||||||
|
|
||||||
|
A handler receives the request's `args` table (never `nil`) and returns one of:
|
||||||
|
|
||||||
|
| Return | Meaning |
|
||||||
|
|---------------------------------|-------------------------------------------------|
|
||||||
|
| `true, data` | Success. `data` is any JSON-serializable table. |
|
||||||
|
| `false, "CODE", "message"` | A normal, expected failure. |
|
||||||
|
|
||||||
|
- **Error codes are free-form strings.** The built-in codes (`SCHEMA_ERROR`, `OP_NOT_ALLOWED`, `RATE_LIMITED`, and so on) are used by the bridge itself, but you can return any code of your own.
|
||||||
|
- **A handler that throws** is caught by the bridge. The caller receives `INTERNAL_ERROR` and the real Lua error is logged server-side only. It never reaches the client.
|
||||||
|
- **`argsSchema`** is optional and shallow. It maps each required top-level argument to a Lua type name (`"string"`, `"number"`, `"boolean"`, `"table"`). A missing or wrongly typed argument is rejected with `SCHEMA_ERROR` before your handler runs. Anything more specific (ranges, nested shapes, optional arguments) is your handler's job to check.
|
||||||
|
- **Handlers run synchronously on the server tick.** Keep them fast, and do not block.
|
||||||
|
|
||||||
|
### Naming
|
||||||
|
|
||||||
|
Op names are flat `snake_case`, verb first, with no dots. All ops share one namespace, this mod's own included, and registering an existing name silently replaces it. Prefix yours with your mod's name (`mymod_get_stash`) to avoid collisions.
|
||||||
|
|
||||||
|
## Things to know before you ship
|
||||||
|
|
||||||
|
**Keep responses small.** Responses travel through a single server option with a payload budget of about 4 KB of JSON, shared by every response the bridge currently holds. A single response larger than that budget is never delivered, and the caller simply times out. Return summaries, and paginate large collections with a cursor argument (see how `list_players` does it).
|
||||||
|
|
||||||
|
**Requests are rate limited and idempotent.** There is one global limit (10 requests per 10 seconds by default, admin-tunable in the mod's Sandbox Options). A caller that re-sends the same request `id` within 60 seconds gets the original cached response back and your handler does not run again. This protects side-effecting ops from retries, but it also means a handler is not guaranteed to run once per call.
|
||||||
|
|
||||||
|
**Admins can switch your op off.** The `set_op_enabled` operation lets an admin disable any non-core op at runtime. A disabled op answers `OP_NOT_ALLOWED`. That state lives in memory only and resets on restart.
|
||||||
|
|
||||||
|
**Removing an op.** `RDB_OpRegistry.unregister("mymod_get_stash")` removes it entirely. You rarely need this, since ops last until the server stops.
|
||||||
|
|
||||||
|
**Discovery.** Registered ops appear in `RconDataBridge_ProtocolVersion` (the `ops` array) and in the `list_ops` operation, which also reports whether each op is enabled.
|
||||||
|
|
||||||
|
## Calling an op
|
||||||
|
|
||||||
|
The wire protocol is the same for every op, built-in or not. A request is a compact JSON **array** of envelopes, base64 encoded, written with `changeoption`:
|
||||||
|
|
||||||
|
```
|
||||||
|
changeoption RconDataBridge_Request <base64>
|
||||||
|
```
|
||||||
|
|
||||||
|
where the decoded payload is:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[{"v":2,"id":"any-unique-id","op":"mymod_get_stash","args":{"name":"north"}}]
|
||||||
|
```
|
||||||
|
|
||||||
|
Responses appear (also base64 encoded) in `RconDataBridge_Response`, as an array you filter by `id`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[{"v":2,"id":"any-unique-id","ok":true,"data":{"name":"north","items":12}}]
|
||||||
|
```
|
||||||
|
|
||||||
|
Requests must be compact JSON with no whitespace, and the whole decoded batch is limited to 4096 bytes. Several envelopes can share one `changeoption` call, and they are queued and processed in order.
|
||||||
|
|
||||||
|
Rather than speak this by hand, use the companion TypeScript client, `rcon-data-bridge-client`. Give it a [Zod](https://zod.dev) schema for your op and you get validated, fully typed results:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { z } from "zod";
|
||||||
|
import { RconDataBridgeClient } from "rcon-data-bridge-client";
|
||||||
|
|
||||||
|
const client = await RconDataBridgeClient.connect({ host: "127.0.0.1", port: 27015, password: "..." });
|
||||||
|
|
||||||
|
const Stash = z.object({ name: z.string(), items: z.number() });
|
||||||
|
const stash = await client.with(Stash).call("mymod_get_stash", { name: "north" });
|
||||||
|
// stash: { name: string; items: number }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing your op locally
|
||||||
|
|
||||||
|
1. Enable both mods on a dedicated server and set an `RCONPort` and `RCONPassword` in its `.ini`.
|
||||||
|
2. Start the server and wait for `[RconDataBridge] INFO: bootstrap complete` in the log.
|
||||||
|
3. Call `list_ops` and check that your op is listed.
|
||||||
|
4. Call your op. Lua changes need a full server restart, since there is no hot reload.
|
||||||
|
|
||||||
|
The `IllegalArgumentException` lines from `ServerOptions.addOption` during boot are harmless. They appear when the save already contains the bridge's options from a previous run.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
AGPL-3.0-or-later. See `LICENSE`.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
*.tsbuildinfo
|
||||||
|
*.tgz
|
||||||
|
|
||||||
|
package-lock.json
|
||||||
|
|
||||||
|
!README.md
|
||||||
+235
@@ -0,0 +1,235 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
pz-rcon-data-bridge
|
||||||
|
Copyright (C) 2026 Overlord
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# rcon-data-bridge-client
|
||||||
|
|
||||||
|
Small, typed TypeScript/Node client for RconDataBridge's v2 RCON protocol:
|
||||||
|
batched/queued requests, typed per-op args/data, and runtime response
|
||||||
|
validation, all over a plain RCON connection (no extra port, no extra auth).
|
||||||
|
|
||||||
|
Talks raw Source RCON over TCP (`node:net`), including a workaround for
|
||||||
|
large responses arriving split across multiple RCON packets; no external
|
||||||
|
RCON library dependency.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { RconDataBridgeClient, RconDataBridgeError } from "rcon-data-bridge-client";
|
||||||
|
|
||||||
|
const client = await RconDataBridgeClient.connect({
|
||||||
|
host: "127.0.0.1",
|
||||||
|
port: 27015,
|
||||||
|
password: "password",
|
||||||
|
});
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Fully typed against the op's schema.
|
||||||
|
const status = await client.call("get_bridge_status");
|
||||||
|
console.log(status.uptimeSeconds);
|
||||||
|
|
||||||
|
// Batch several requests into one RCON round trip; results come back as
|
||||||
|
// a tuple, one entry per request, in order.
|
||||||
|
const [worldStats, players] = await client.batch([
|
||||||
|
{ op: "get_world_stats" },
|
||||||
|
{ op: "list_players", args: { limit: 20 } },
|
||||||
|
]);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await client.call("get_player", { id: "no-such-player" });
|
||||||
|
}
|
||||||
|
catch (err)
|
||||||
|
{
|
||||||
|
if (err instanceof RconDataBridgeError) {
|
||||||
|
console.log(err.code, err.message); // "PLAYER_NOT_FOUND", ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { client.close(); }
|
||||||
|
```
|
||||||
|
|
||||||
|
An op this client has no built-in schema for (e.g. a server-side plugin
|
||||||
|
extension) can still be validated. Bind a Zod schema with `with()` and call
|
||||||
|
through that instead of `client` directly. `.call` on the returned object
|
||||||
|
has the same `(op, args?, options?)` shape as `client.call` itself, but it
|
||||||
|
validates against the bound schema and infers its return type from it
|
||||||
|
instead of taking a type argument:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const MyOpResultSchema = z.object({ status: z.string() });
|
||||||
|
|
||||||
|
const data = await client.with(MyOpResultSchema).call("some_custom_op", { targetId: "x" });
|
||||||
|
// data: { status: string }, already validated
|
||||||
|
```
|
||||||
|
|
||||||
|
Or skip validation entirely and just trust a type you supply yourself:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface MyOpResult {
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await client.call<MyOpResult>("some_custom_op", { targetId: "x" });
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Responses are validated, not just typed.** Every op's response is
|
||||||
|
checked against a [Zod](https://zod.dev) schema, built-in for known ops,
|
||||||
|
or your own via `with()`, so a bad response throws a clear
|
||||||
|
`RconDataBridgeSchemaMismatchError` instead of handing you the wrong shape.
|
||||||
|
- **Polling speeds up while you're active, then eases off.** It polls fast
|
||||||
|
right after you submit something and slows down once things go quiet. Tune
|
||||||
|
both speeds, and the window between them, via
|
||||||
|
`RconDataBridgeClient.connect`'s options.
|
||||||
|
- **One client, one connection.** Don't overlap `call`/`batch` calls on the
|
||||||
|
same client. Await one before starting the next, or just open a second
|
||||||
|
client.
|
||||||
|
|
||||||
|
## Live-testing against a running server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
RDB_HOST=127.0.0.1 RDB_PORT=27015 RDB_PASSWORD=password npm run smoke
|
||||||
|
```
|
||||||
|
|
||||||
|
`tests/smoke.mjs` is not a unit test suite. It exercises real ops over a real
|
||||||
|
RCON connection against a running server and fails loudly on any mismatch.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "rcon-data-bridge-client",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "TypeScript/Node client for RconDataBridge's v2 RCON protocol (batched requests, queueing, plugin op introspection).",
|
||||||
|
"type": "module",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"default": "./dist/index.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"smoke": "npm run build && node tests/smoke.mjs",
|
||||||
|
"prepack": "npm run build"
|
||||||
|
},
|
||||||
|
"license": "AGPL-3.0-or-later",
|
||||||
|
"dependencies": {
|
||||||
|
"zod": "^3.23.8"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.5.0",
|
||||||
|
"typescript": "^5.6.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { RconTransport, type RconTransportOptions } from "./transport.js";
|
||||||
|
import { decodeBase64, encodeBase64, encodeCompactJson, OPT, parseShowOptions } from "./protocol.js";
|
||||||
|
import {
|
||||||
|
OpSchemas,
|
||||||
|
PROTOCOL_VERSION,
|
||||||
|
ResponseBatchSchema,
|
||||||
|
ResponseEnvelopeSchema,
|
||||||
|
type OpArgs,
|
||||||
|
type OpData,
|
||||||
|
type OpName,
|
||||||
|
type ResponseEnvelope,
|
||||||
|
} from "./schemas.js";
|
||||||
|
import { RconDataBridgeError, RconDataBridgeSchemaMismatchError, RconDataBridgeTimeoutError } from "./errors.js";
|
||||||
|
|
||||||
|
export interface RconDataBridgeClientOptions extends RconTransportOptions {
|
||||||
|
/** How often to poll while within activeWindowMs of submitting a batch.
|
||||||
|
* Default 200ms -- right after you submit something the server is very
|
||||||
|
* likely still processing it, so polling quickly here is cheap and
|
||||||
|
* low-latency. */
|
||||||
|
activePollIntervalMs?: number;
|
||||||
|
/** How long after submitting a batch to keep polling at
|
||||||
|
* activePollIntervalMs before backing off. Default 10000ms, matching
|
||||||
|
* the server's default ActiveWindowSeconds. */
|
||||||
|
activeWindowMs?: number;
|
||||||
|
/** Poll interval once activeWindowMs has elapsed without every response
|
||||||
|
* showing up yet. Default 1000ms. */
|
||||||
|
idlePollIntervalMs?: number;
|
||||||
|
/** Overall timeout for waiting out a batch's responses. Default 15000ms. */
|
||||||
|
defaultTimeoutMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CallOptions {
|
||||||
|
/** Overrides defaultTimeoutMs for this one call/batch. */
|
||||||
|
timeoutMs?: number;
|
||||||
|
/** Overrides the auto-generated request id. Only useful for deliberate
|
||||||
|
* idempotent retries -- resubmitting the same id replays the cached
|
||||||
|
* response instead of running the op again. */
|
||||||
|
id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returned by `RconDataBridgeClient.with(schema)` -- see there. */
|
||||||
|
export interface SchemaBoundCaller<TSchema extends z.ZodType> {
|
||||||
|
call(op: string, args?: Record<string, unknown>, options?: CallOptions): Promise<z.infer<TSchema>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BatchRequest<K extends OpName> {
|
||||||
|
op: K;
|
||||||
|
args?: OpArgs<K>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type BatchResult<T extends readonly BatchRequest<OpName>[]> = {
|
||||||
|
[I in keyof T]: T[I] extends BatchRequest<infer K> ? OpData<K> : never;
|
||||||
|
};
|
||||||
|
|
||||||
|
const RESOLVED_DEFAULTS = {
|
||||||
|
activePollIntervalMs: 200,
|
||||||
|
activeWindowMs: 10_000,
|
||||||
|
idlePollIntervalMs: 1_000,
|
||||||
|
defaultTimeoutMs: 15_000,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Small, typed client for RconDataBridge's v2 protocol -- batched/queued
|
||||||
|
* requests over RCON `changeoption`/`showoptions`. One instance = one RCON
|
||||||
|
* connection; not internally concurrency-safe for overlapping
|
||||||
|
* `call`/`batch` invocations (each does its own submit-then-poll cycle
|
||||||
|
* against the shared `RconDataBridge_Request`/`Response` options) -- await
|
||||||
|
* one before starting the next, or open multiple clients.
|
||||||
|
*/
|
||||||
|
export class RconDataBridgeClient {
|
||||||
|
private readonly transport: RconTransport;
|
||||||
|
private readonly options: Required<
|
||||||
|
Pick<RconDataBridgeClientOptions, "activePollIntervalMs" | "activeWindowMs" | "idlePollIntervalMs" | "defaultTimeoutMs">
|
||||||
|
>;
|
||||||
|
|
||||||
|
private constructor(transport: RconTransport, options: RconDataBridgeClientOptions) {
|
||||||
|
this.transport = transport;
|
||||||
|
this.options = {
|
||||||
|
activePollIntervalMs: options.activePollIntervalMs ?? RESOLVED_DEFAULTS.activePollIntervalMs,
|
||||||
|
activeWindowMs: options.activeWindowMs ?? RESOLVED_DEFAULTS.activeWindowMs,
|
||||||
|
idlePollIntervalMs: options.idlePollIntervalMs ?? RESOLVED_DEFAULTS.idlePollIntervalMs,
|
||||||
|
defaultTimeoutMs: options.defaultTimeoutMs ?? RESOLVED_DEFAULTS.defaultTimeoutMs,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static async connect(options: RconDataBridgeClientOptions): Promise<RconDataBridgeClient> {
|
||||||
|
const transport = await RconTransport.connect(options);
|
||||||
|
return new RconDataBridgeClient(transport, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.transport.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs any raw RCON command and returns its (already
|
||||||
|
* chunk-reassembled) body -- an escape hatch for anything outside
|
||||||
|
* RconDataBridge's own protocol. */
|
||||||
|
async raw(command: string): Promise<string> {
|
||||||
|
return this.transport.command(command);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads and decodes RconDataBridge_ProtocolVersion directly -- no
|
||||||
|
* request/response round trip needed for this one. */
|
||||||
|
async getProtocolVersion(): Promise<unknown> {
|
||||||
|
const options = await this.readOptions();
|
||||||
|
const raw = options.get(OPT.PROTOCOL_VERSION);
|
||||||
|
return raw ? JSON.parse(decodeBase64(raw)) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads and decodes the cached RconDataBridge_WorldStats directly --
|
||||||
|
* refreshed ~once a minute server-side regardless of any client
|
||||||
|
* calling get_world_stats, so prefer this over a round trip when you
|
||||||
|
* don't need a guaranteed-fresh read. */
|
||||||
|
async getCachedWorldStats(): Promise<OpData<"get_world_stats"> | undefined> {
|
||||||
|
const options = await this.readOptions();
|
||||||
|
const raw = options.get(OPT.WORLD_STATS);
|
||||||
|
if (!raw) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return OpSchemas.get_world_stats.data.parse(JSON.parse(decodeBase64(raw)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a known op, fully typed and validated against OpSchemas. */
|
||||||
|
async call<K extends OpName>(op: K, args?: OpArgs<K>, options?: CallOptions): Promise<OpData<K>>;
|
||||||
|
/** Runs an op this client has neither a built-in nor an ad-hoc schema for
|
||||||
|
* -- pass the expected return type explicitly, `call<MyType>("my_op",
|
||||||
|
* args)`. No validation at all; you get back whatever `data` the server
|
||||||
|
* sent, cast to `TData` on trust. Prefer `with(schema).call(...)` (see
|
||||||
|
* below) when you can, for an op you *do* have or can write a schema
|
||||||
|
* for. */
|
||||||
|
async call<TData = unknown, TArgs extends Record<string, unknown> = Record<string, unknown>>(
|
||||||
|
op: string,
|
||||||
|
args?: TArgs,
|
||||||
|
options?: CallOptions,
|
||||||
|
): Promise<TData>;
|
||||||
|
async call(op: string, args?: Record<string, unknown>, options?: CallOptions): Promise<unknown> {
|
||||||
|
return this.resolveCall(op, args, options, undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Binds a Zod schema for ops this client has no built-in schema for
|
||||||
|
* (e.g. a server-side plugin extension) -- `.call(op, args?, options?)`
|
||||||
|
* on the returned object has the exact same shape as this client's own
|
||||||
|
* `call`, just validates against `schema` and infers its return type
|
||||||
|
* from it instead of taking a type argument:
|
||||||
|
* `client.with(MySchema).call("my_op", args)`. Kept as a separate
|
||||||
|
* method rather than a third `call` overload so `args` stays the second
|
||||||
|
* positional argument everywhere, instead of shifting position
|
||||||
|
* depending on whether a schema is involved. */
|
||||||
|
with<TSchema extends z.ZodType>(schema: TSchema): SchemaBoundCaller<TSchema> {
|
||||||
|
return {
|
||||||
|
call: (op, args, options) => this.resolveCall(op, args, options, schema) as Promise<z.infer<TSchema>>,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveCall(
|
||||||
|
op: string,
|
||||||
|
args: Record<string, unknown> | undefined,
|
||||||
|
options: CallOptions | undefined,
|
||||||
|
adHocSchema: z.ZodType | undefined,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const id = options?.id ?? randomUUID();
|
||||||
|
const responses = await this.submitAndWait([{ v: PROTOCOL_VERSION, id, op, args: args ?? {} }], options);
|
||||||
|
const response = responses.get(id);
|
||||||
|
|
||||||
|
if (!response) {
|
||||||
|
throw new RconDataBridgeTimeoutError(id, options?.timeoutMs ?? this.options.defaultTimeoutMs);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new RconDataBridgeError(response.error.code, response.error.message, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const schema = adHocSchema ?? (OpSchemas as Partial<Record<string, { data: z.ZodType }>>)[op]?.data;
|
||||||
|
if (!schema) {
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return schema.parse(response.data);
|
||||||
|
} catch (cause) {
|
||||||
|
throw new RconDataBridgeSchemaMismatchError(op, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Submits several requests as one batch (one `changeoption` call) and
|
||||||
|
* returns their results in the same order as `requests`, fully typed
|
||||||
|
* per-entry. Throws on the first entry that errored or timed out
|
||||||
|
* (checked in submission order), same as `call`. */
|
||||||
|
async batch<T extends readonly BatchRequest<OpName>[]>(requests: [...T], options?: CallOptions): Promise<BatchResult<T>> {
|
||||||
|
const ids = requests.map(() => randomUUID());
|
||||||
|
const envelopes = requests.map((request, i) => ({
|
||||||
|
v: PROTOCOL_VERSION,
|
||||||
|
id: ids[i] as string,
|
||||||
|
op: request.op,
|
||||||
|
args: (request.args ?? {}) as Record<string, unknown>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const responses = await this.submitAndWait(envelopes, options);
|
||||||
|
|
||||||
|
const results: unknown[] = [];
|
||||||
|
for (let i = 0; i < requests.length; i++) {
|
||||||
|
const request = requests[i] as T[number];
|
||||||
|
const id = ids[i] as string;
|
||||||
|
const response = responses.get(id);
|
||||||
|
|
||||||
|
if (!response) {
|
||||||
|
throw new RconDataBridgeTimeoutError(id, options?.timeoutMs ?? this.options.defaultTimeoutMs);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new RconDataBridgeError(response.error.code, response.error.message, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
results.push(OpSchemas[request.op].data.parse(response.data));
|
||||||
|
} catch (cause) {
|
||||||
|
throw new RconDataBridgeSchemaMismatchError(request.op, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results as BatchResult<T>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- internals -----------------------------------------------------
|
||||||
|
|
||||||
|
private async readOptions(): Promise<Map<string, string>> {
|
||||||
|
return parseShowOptions(await this.transport.command("showoptions"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async submitAndWait(
|
||||||
|
envelopes: ReadonlyArray<{ v: number; id: string; op: string; args: Record<string, unknown> }>,
|
||||||
|
options?: CallOptions,
|
||||||
|
): Promise<Map<string, ResponseEnvelope>> {
|
||||||
|
const timeoutMs = options?.timeoutMs ?? this.options.defaultTimeoutMs;
|
||||||
|
const payload = encodeBase64(encodeCompactJson(envelopes));
|
||||||
|
await this.transport.command(`changeoption ${OPT.REQUEST} ${payload}`);
|
||||||
|
|
||||||
|
const wanted = new Set(envelopes.map((e) => e.id));
|
||||||
|
const found = new Map<string, ResponseEnvelope>();
|
||||||
|
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
const submittedAt = Date.now();
|
||||||
|
|
||||||
|
while (Date.now() < deadline && found.size < wanted.size) {
|
||||||
|
const optionsMap = await this.readOptions();
|
||||||
|
const raw = optionsMap.get(OPT.RESPONSE);
|
||||||
|
if (raw) {
|
||||||
|
const decoded = JSON.parse(decodeBase64(raw));
|
||||||
|
const entries = ResponseBatchSchema.safeParse(decoded);
|
||||||
|
for (const entry of entries.success ? entries.data : []) {
|
||||||
|
const parsed = ResponseEnvelopeSchema.safeParse(entry);
|
||||||
|
if (parsed.success && wanted.has(parsed.data.id)) {
|
||||||
|
found.set(parsed.data.id, parsed.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (found.size >= wanted.size) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const withinActiveWindow = Date.now() - submittedAt < this.options.activeWindowMs;
|
||||||
|
const delay = withinActiveWindow ? this.options.activePollIntervalMs : this.options.idlePollIntervalMs;
|
||||||
|
await sleep(delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import type { ErrorCode } from "./schemas.js";
|
||||||
|
|
||||||
|
/** A well-formed `{ok:false}` response from the bridge -- a normal error
|
||||||
|
* condition (bad args, rate limited, queue full, ...), not a transport or
|
||||||
|
* client bug. */
|
||||||
|
export class RconDataBridgeError extends Error {
|
||||||
|
constructor(
|
||||||
|
readonly code: ErrorCode,
|
||||||
|
message: string,
|
||||||
|
readonly requestId: string,
|
||||||
|
) {
|
||||||
|
super(`[${code}] ${message}`);
|
||||||
|
this.name = "RconDataBridgeError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A request never got a response within the configured timeout. Could mean
|
||||||
|
* the server never saw it, never finished it, or finished it but the
|
||||||
|
* response didn't make it into any poll this client made before giving
|
||||||
|
* up. */
|
||||||
|
export class RconDataBridgeTimeoutError extends Error {
|
||||||
|
constructor(readonly requestId: string, timeoutMs: number) {
|
||||||
|
super(`Timed out after ${timeoutMs}ms waiting for a response to request id "${requestId}"`);
|
||||||
|
this.name = "RconDataBridgeTimeoutError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's response didn't match the schema it was validated against --
|
||||||
|
* either this client's built-in schema for a known op (almost always a
|
||||||
|
* protocol-version mismatch between this client and the server it's talking
|
||||||
|
* to; compare RconDataBridge_ProtocolVersion against PROTOCOL_VERSION) or an
|
||||||
|
* ad-hoc schema passed to `call` for an op this client has no built-in
|
||||||
|
* schema for (check that schema against what the op actually returns). */
|
||||||
|
export class RconDataBridgeSchemaMismatchError extends Error {
|
||||||
|
constructor(op: string, cause: unknown) {
|
||||||
|
super(`Response to op "${op}" didn't match the schema it was validated against`, { cause });
|
||||||
|
this.name = "RconDataBridgeSchemaMismatchError";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
export { RconDataBridgeClient } from "./client.js";
|
||||||
|
export type { RconDataBridgeClientOptions, CallOptions, SchemaBoundCaller } from "./client.js";
|
||||||
|
|
||||||
|
export { RconDataBridgeError, RconDataBridgeTimeoutError, RconDataBridgeSchemaMismatchError } from "./errors.js";
|
||||||
|
|
||||||
|
export { RconAuthError, RconTransport } from "./transport.js";
|
||||||
|
export type { RconTransportOptions } from "./transport.js";
|
||||||
|
|
||||||
|
export { OpSchemas, PROTOCOL_VERSION, PlayerSnapshotSchema, ErrorCodeSchema } from "./schemas.js";
|
||||||
|
export type { OpName, OpArgs, OpData, PlayerSnapshot, ErrorCode, ResponseEnvelope } from "./schemas.js";
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
// Wire-level encode/decode helpers -- base64 (every RconDataBridge_* option
|
||||||
|
// value, both directions, no exceptions), compact JSON (RCON's tokenizer
|
||||||
|
// splits an unquoted literal space into multiple arguments, so no
|
||||||
|
// whitespace), and parsing raw `showoptions` text output.
|
||||||
|
|
||||||
|
export const OPTION_PREFIX = "RconDataBridge_";
|
||||||
|
|
||||||
|
export const OPT = {
|
||||||
|
PROTOCOL_VERSION: "RconDataBridge_ProtocolVersion",
|
||||||
|
WORLD_STATS: "RconDataBridge_WorldStats",
|
||||||
|
REQUEST: "RconDataBridge_Request",
|
||||||
|
RESPONSE: "RconDataBridge_Response",
|
||||||
|
LAST_RESPONSE: "RconDataBridge_LastResponse",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function encodeBase64(raw: string): string {
|
||||||
|
return Buffer.from(raw, "utf8").toString("base64");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeBase64(encoded: string): string {
|
||||||
|
return Buffer.from(encoded, "base64").toString("utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compact (no-whitespace) JSON -- JSON.stringify already produces this with
|
||||||
|
* no `space` argument; this wrapper exists so the "must be compact" rule
|
||||||
|
* has one obvious call site instead of relying on every caller remembering
|
||||||
|
* not to pass one. */
|
||||||
|
export function encodeCompactJson(value: unknown): string {
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses one `showoptions` response body into a name -> raw (still
|
||||||
|
* base64-encoded) value map, for every `RconDataBridge_*` option present.
|
||||||
|
* Each line looks like `* RconDataBridge_Foo=<base64>`.
|
||||||
|
*/
|
||||||
|
export function parseShowOptions(raw: string): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
|
||||||
|
for (const line of raw.split("\n"))
|
||||||
|
{
|
||||||
|
const trimmed = line.trimEnd();
|
||||||
|
if (!trimmed.startsWith(`* ${OPTION_PREFIX}`)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const withoutMarker = trimmed.slice(2);
|
||||||
|
const eqIndex = withoutMarker.indexOf("=");
|
||||||
|
if (eqIndex === -1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const name = withoutMarker.slice(0, eqIndex);
|
||||||
|
const value = withoutMarker.slice(eqIndex + 1);
|
||||||
|
out.set(name, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
// Single source of truth for the wire protocol's shapes. Every exported
|
||||||
|
// TypeScript type here is `z.infer`red from the schema right next to it --
|
||||||
|
// one place to update when the protocol changes, and a schema mismatch
|
||||||
|
// between this client and a live server surfaces as a runtime error
|
||||||
|
// instead of a silent type-shape lie.
|
||||||
|
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const PROTOCOL_VERSION = 2;
|
||||||
|
|
||||||
|
export const ErrorCodeSchema = z.enum([
|
||||||
|
"SCHEMA_ERROR",
|
||||||
|
"PAYLOAD_TOO_LARGE",
|
||||||
|
"OP_NOT_ALLOWED",
|
||||||
|
"RATE_LIMITED",
|
||||||
|
"PLAYER_NOT_FOUND",
|
||||||
|
"SAVE_FAILED",
|
||||||
|
"INTERNAL_ERROR",
|
||||||
|
"QUEUE_FULL",
|
||||||
|
"CORE_OP_PROTECTED",
|
||||||
|
]);
|
||||||
|
export type KnownErrorCode = z.infer<typeof ErrorCodeSchema>;
|
||||||
|
/** Built-in codes autocomplete, but any string is valid: plugin ops can
|
||||||
|
* return their own. */
|
||||||
|
export type ErrorCode = KnownErrorCode | (string & {});
|
||||||
|
|
||||||
|
export const ResponseEnvelopeSchema = z.discriminatedUnion("ok", [
|
||||||
|
z.object({
|
||||||
|
v: z.number(),
|
||||||
|
id: z.string(),
|
||||||
|
ok: z.literal(true),
|
||||||
|
data: z.unknown(),
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
v: z.number(),
|
||||||
|
id: z.string(),
|
||||||
|
ok: z.literal(false),
|
||||||
|
error: z.object({
|
||||||
|
code: z.string(),
|
||||||
|
message: z.string(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
export type ResponseEnvelope = z.infer<typeof ResponseEnvelopeSchema>;
|
||||||
|
|
||||||
|
export const ResponseBatchSchema = z.array(z.unknown());
|
||||||
|
|
||||||
|
// --- Player snapshot (shared by get_player and list_players) ---------------
|
||||||
|
|
||||||
|
export const PlayerSnapshotSchema = z.object({
|
||||||
|
id: z.string(),
|
||||||
|
online: z.boolean(),
|
||||||
|
characterId: z.number(),
|
||||||
|
lastSeenAt: z.number(),
|
||||||
|
stats: z.object({
|
||||||
|
hoursSurvived: z.number(),
|
||||||
|
zombiesKilled: z.number(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
export type PlayerSnapshot = z.infer<typeof PlayerSnapshotSchema>;
|
||||||
|
|
||||||
|
// --- Per-op args/data schemas ----------------------------------------------
|
||||||
|
// Keys here are the exact `op` strings the server recognizes.
|
||||||
|
|
||||||
|
const EmptyArgs = z.object({}).strict();
|
||||||
|
|
||||||
|
export const OpSchemas = {
|
||||||
|
get_world_stats: {
|
||||||
|
args: EmptyArgs,
|
||||||
|
data: z.object({
|
||||||
|
worldAgeHours: z.number(),
|
||||||
|
worldAgeDays: z.number(),
|
||||||
|
nightsSurvived: z.number(),
|
||||||
|
date: z.object({
|
||||||
|
year: z.number(),
|
||||||
|
month: z.number(),
|
||||||
|
day: z.number(),
|
||||||
|
hour: z.number(),
|
||||||
|
minute: z.number(),
|
||||||
|
}),
|
||||||
|
isNight: z.boolean(),
|
||||||
|
isRaining: z.boolean(),
|
||||||
|
timeMultiplier: z.number(),
|
||||||
|
generatedAt: z.number(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
get_player: {
|
||||||
|
args: z.object({ id: z.string() }),
|
||||||
|
data: PlayerSnapshotSchema,
|
||||||
|
},
|
||||||
|
|
||||||
|
list_players: {
|
||||||
|
args: z.object({
|
||||||
|
limit: z.number().optional(),
|
||||||
|
cursor: z.string().optional(),
|
||||||
|
}),
|
||||||
|
data: z.object({
|
||||||
|
players: z.array(PlayerSnapshotSchema),
|
||||||
|
nextCursor: z.string().optional(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
save_server: {
|
||||||
|
args: EmptyArgs,
|
||||||
|
data: z.object({ triggered: z.literal(true) }),
|
||||||
|
},
|
||||||
|
|
||||||
|
get_bridge_status: {
|
||||||
|
args: EmptyArgs,
|
||||||
|
data: z.object({
|
||||||
|
version: z.number(),
|
||||||
|
bootedAt: z.number(),
|
||||||
|
uptimeSeconds: z.number(),
|
||||||
|
paused: z.boolean(),
|
||||||
|
rateLimit: z.object({
|
||||||
|
currentWindowRequests: z.number(),
|
||||||
|
maxRequests: z.number(),
|
||||||
|
windowSeconds: z.number(),
|
||||||
|
}),
|
||||||
|
// Admin-tunable sandbox config, deliberately open-ended rather
|
||||||
|
// than enumerated field-by-field: it's observability output,
|
||||||
|
// not a contract this client should break on a new/renamed
|
||||||
|
// field the server adds.
|
||||||
|
config: z.record(z.string(), z.unknown()),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
get_audit_log: {
|
||||||
|
args: z.object({ limit: z.number().optional() }),
|
||||||
|
data: z.object({
|
||||||
|
entries: z.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string(),
|
||||||
|
op: z.string(),
|
||||||
|
ok: z.boolean(),
|
||||||
|
code: z.string().optional(),
|
||||||
|
ts: z.number(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
get_queue_status: {
|
||||||
|
args: EmptyArgs,
|
||||||
|
data: z.object({
|
||||||
|
depth: z.number(),
|
||||||
|
oldestEnqueuedAt: z.number().nullable(),
|
||||||
|
requestsPerTick: z.number(),
|
||||||
|
maxQueueDepth: z.number(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
list_ops: {
|
||||||
|
args: EmptyArgs,
|
||||||
|
data: z.object({
|
||||||
|
ops: z.array(
|
||||||
|
z.object({
|
||||||
|
name: z.string(),
|
||||||
|
core: z.boolean(),
|
||||||
|
enabled: z.boolean(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
set_op_enabled: {
|
||||||
|
args: z.object({ name: z.string(), enabled: z.boolean() }),
|
||||||
|
data: z.object({ name: z.string(), enabled: z.boolean() }),
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type OpName = keyof typeof OpSchemas;
|
||||||
|
export type OpArgs<K extends OpName> = z.infer<(typeof OpSchemas)[K]["args"]>;
|
||||||
|
export type OpData<K extends OpName> = z.infer<(typeof OpSchemas)[K]["data"]>;
|
||||||
|
|
||||||
|
// An op not listed here (e.g. a server-side plugin extension) has no schema
|
||||||
|
// in this client -- still callable via RconDataBridgeClient.call<TData>(),
|
||||||
|
// or RconDataBridgeClient.with(ZodSchema).call().
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
// Raw Source RCON transport over TCP, no external RCON library dependency.
|
||||||
|
// PZ's RCON server can split a response across multiple packets sharing
|
||||||
|
// the same request id, with no end-of-response marker -- a client that
|
||||||
|
// resolves on the first packet silently truncates anything larger. This
|
||||||
|
// works around it by sending a cheap throwaway command right after the
|
||||||
|
// real one and reading until *its* response shows up: RCON servers handle
|
||||||
|
// commands strictly in order, so every chunk of the real response is
|
||||||
|
// guaranteed to have already arrived by the time the trailer's response
|
||||||
|
// does.
|
||||||
|
|
||||||
|
import { Socket } from "node:net";
|
||||||
|
|
||||||
|
const SERVERDATA_AUTH = 3;
|
||||||
|
const SERVERDATA_EXECCOMMAND = 2;
|
||||||
|
const SERVERDATA_RESPONSE_VALUE = 0;
|
||||||
|
|
||||||
|
const TRAILER_COMMAND = "rcon_client_trailer_noop";
|
||||||
|
|
||||||
|
interface RawPacket {
|
||||||
|
id: number;
|
||||||
|
type: number;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RconTransportOptions {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
password: string;
|
||||||
|
/** Connection + auth timeout, in ms. Default 10000. */
|
||||||
|
connectTimeoutMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Thrown when the RCON server rejects the configured password. */
|
||||||
|
export class RconAuthError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super("RCON authentication failed -- check host/port/password");
|
||||||
|
this.name = "RconAuthError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buffers raw socket bytes and yields complete Source RCON packets as they
|
||||||
|
// become available. A packet is never split across two `parse()` calls by
|
||||||
|
// the caller -- this class owns re-assembly across TCP fragmentation.
|
||||||
|
class PacketReassembler {
|
||||||
|
private buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
|
||||||
|
|
||||||
|
push(chunk: Buffer<ArrayBufferLike>): RawPacket[] {
|
||||||
|
this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]);
|
||||||
|
|
||||||
|
const packets: RawPacket[] = [];
|
||||||
|
for (;;) {
|
||||||
|
if (this.buffer.length < 4) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size = this.buffer.readInt32LE(0);
|
||||||
|
const totalLength = 4 + size;
|
||||||
|
if (this.buffer.length < totalLength) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = this.buffer.readInt32LE(4);
|
||||||
|
const type = this.buffer.readInt32LE(8);
|
||||||
|
// Body runs from byte 12 to end-of-packet minus the two
|
||||||
|
// trailing null bytes (string terminator + packet terminator).
|
||||||
|
const body = this.buffer.subarray(12, totalLength - 2).toString("utf8");
|
||||||
|
packets.push({ id, type, body });
|
||||||
|
|
||||||
|
this.buffer = this.buffer.subarray(totalLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
return packets;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodePacket(id: number, type: number, body: string): Buffer {
|
||||||
|
const bodyBuf = Buffer.from(body, "utf8");
|
||||||
|
const payload = Buffer.alloc(4 + 4 + bodyBuf.length + 2);
|
||||||
|
payload.writeInt32LE(id, 0);
|
||||||
|
payload.writeInt32LE(type, 4);
|
||||||
|
bodyBuf.copy(payload, 8);
|
||||||
|
// trailing bytes already zeroed by Buffer.alloc
|
||||||
|
|
||||||
|
const framed = Buffer.alloc(4 + payload.length);
|
||||||
|
framed.writeInt32LE(payload.length, 0);
|
||||||
|
payload.copy(framed, 4);
|
||||||
|
return framed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single authenticated RCON connection. Not safe for concurrent
|
||||||
|
* `command()` calls -- it issues one request+trailer pair at a time and
|
||||||
|
* waits for the trailer's response before returning. Callers wanting
|
||||||
|
* concurrency should open multiple `RconTransport` instances, or
|
||||||
|
* (preferably) batch multiple requests into one `command()` call instead --
|
||||||
|
* see `RconDataBridgeClient`.
|
||||||
|
*/
|
||||||
|
export class RconTransport {
|
||||||
|
private readonly socket: Socket;
|
||||||
|
private readonly reassembler = new PacketReassembler();
|
||||||
|
private nextId = 1;
|
||||||
|
private pendingPackets: RawPacket[] = [];
|
||||||
|
private waiters: Array<() => void> = [];
|
||||||
|
private closed = false;
|
||||||
|
private socketError: Error | null = null;
|
||||||
|
|
||||||
|
private constructor(socket: Socket) {
|
||||||
|
this.socket = socket;
|
||||||
|
socket.on("data", (chunk: Buffer) => {
|
||||||
|
const packets = this.reassembler.push(chunk);
|
||||||
|
if (packets.length > 0) {
|
||||||
|
this.pendingPackets.push(...packets);
|
||||||
|
this.drainWaiters();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
socket.on("error", (err) => {
|
||||||
|
this.socketError = err;
|
||||||
|
this.drainWaiters();
|
||||||
|
});
|
||||||
|
socket.on("close", () => {
|
||||||
|
this.closed = true;
|
||||||
|
this.drainWaiters();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static async connect(options: RconTransportOptions): Promise<RconTransport> {
|
||||||
|
const timeoutMs = options.connectTimeoutMs ?? 10_000;
|
||||||
|
|
||||||
|
const socket = await new Promise<Socket>((resolve, reject) => {
|
||||||
|
const s = new Socket();
|
||||||
|
const onError = (err: Error) => {
|
||||||
|
s.destroy();
|
||||||
|
reject(err);
|
||||||
|
};
|
||||||
|
s.setTimeout(timeoutMs, () => onError(new Error(`Connection to ${options.host}:${options.port} timed out`)));
|
||||||
|
s.once("error", onError);
|
||||||
|
s.connect(options.port, options.host, () => {
|
||||||
|
s.setTimeout(0);
|
||||||
|
s.removeListener("error", onError);
|
||||||
|
resolve(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const transport = new RconTransport(socket);
|
||||||
|
await transport.authenticate(options.password);
|
||||||
|
return transport;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async nextPacket(): Promise<RawPacket> {
|
||||||
|
if (this.pendingPackets.length > 0) {
|
||||||
|
return this.pendingPackets.shift() as RawPacket;
|
||||||
|
}
|
||||||
|
if (this.socketError) {
|
||||||
|
throw this.socketError;
|
||||||
|
}
|
||||||
|
if (this.closed) {
|
||||||
|
throw new Error("RCON socket closed while waiting for a response");
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => this.waiters.push(resolve));
|
||||||
|
return this.nextPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
private drainWaiters(): void {
|
||||||
|
const waiters = this.waiters;
|
||||||
|
this.waiters = [];
|
||||||
|
for (const resolve of waiters) {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private send(id: number, type: number, body: string): void {
|
||||||
|
this.socket.write(encodePacket(id, type, body));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async authenticate(password: string): Promise<void> {
|
||||||
|
const authId = this.nextId++;
|
||||||
|
this.send(authId, SERVERDATA_AUTH, password);
|
||||||
|
|
||||||
|
let packet = await this.nextPacket();
|
||||||
|
// PZ sends an empty SERVERDATA_RESPONSE_VALUE ahead of the real
|
||||||
|
// auth response.
|
||||||
|
if (packet.type === SERVERDATA_RESPONSE_VALUE) {
|
||||||
|
packet = await this.nextPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (packet.id !== authId) {
|
||||||
|
throw new RconAuthError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs one RCON command end to end, returning its full (possibly
|
||||||
|
* multi-packet) response body. */
|
||||||
|
async command(cmd: string): Promise<string> {
|
||||||
|
const realId = this.nextId++;
|
||||||
|
const trailerId = this.nextId++;
|
||||||
|
|
||||||
|
this.send(realId, SERVERDATA_EXECCOMMAND, cmd);
|
||||||
|
this.send(trailerId, SERVERDATA_EXECCOMMAND, TRAILER_COMMAND);
|
||||||
|
|
||||||
|
const parts: string[] = [];
|
||||||
|
for (;;) {
|
||||||
|
const packet = await this.nextPacket();
|
||||||
|
if (packet.id === realId) {
|
||||||
|
parts.push(packet.body);
|
||||||
|
} else if (packet.id === trailerId) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.socket.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// Live smoke test against a running RconDataBridge server. Not a unit test
|
||||||
|
// suite -- exercises real ops over a real RCON connection, against the
|
||||||
|
// built package output, and fails loudly if anything doesn't round-trip.
|
||||||
|
// Run via `npm run smoke`.
|
||||||
|
|
||||||
|
import { z } from "zod";
|
||||||
|
import { RconDataBridgeClient, RconDataBridgeError, RconDataBridgeSchemaMismatchError } from "../dist/index.js";
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const client = await RconDataBridgeClient.connect({
|
||||||
|
host: process.env["RDB_HOST"] ?? "127.0.0.1",
|
||||||
|
port: Number(process.env["RDB_PORT"] ?? 27015),
|
||||||
|
password: process.env["RDB_PASSWORD"] ?? "rdbtestpw123",
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log("== getProtocolVersion (direct option read, no round trip) ==");
|
||||||
|
console.log(await client.getProtocolVersion());
|
||||||
|
|
||||||
|
console.log("== call get_bridge_status ==");
|
||||||
|
const status = await client.call("get_bridge_status");
|
||||||
|
console.log(status);
|
||||||
|
if (status.version !== 2) {
|
||||||
|
throw new Error(`expected protocol version 2, got ${status.version}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("== batch: get_world_stats + list_players + get_queue_status + list_ops ==");
|
||||||
|
const [worldStats, players, queueStatus, ops] = await client.batch([
|
||||||
|
{ op: "get_world_stats" },
|
||||||
|
{ op: "list_players" },
|
||||||
|
{ op: "get_queue_status" },
|
||||||
|
{ op: "list_ops" },
|
||||||
|
]);
|
||||||
|
console.log({ worldStats, players, queueStatus, ops });
|
||||||
|
|
||||||
|
console.log("== call get_player with an unknown id (expect PLAYER_NOT_FOUND) ==");
|
||||||
|
try {
|
||||||
|
await client.call("get_player", { id: "definitely-not-a-real-player" });
|
||||||
|
throw new Error("expected RconDataBridgeError, got a success response");
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof RconDataBridgeError) || err.code !== "PLAYER_NOT_FOUND") {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
console.log(`got expected error: ${err.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("== call<T> unchecked path for an op this client has no schema for ==");
|
||||||
|
try {
|
||||||
|
await client.call("definitely_not_a_real_op");
|
||||||
|
throw new Error("expected RconDataBridgeError, got a success response");
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof RconDataBridgeError) || err.code !== "OP_NOT_ALLOWED") {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
console.log(`unchecked call correctly reached the server and got: ${err.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("== with(schema).call, matching shape ==");
|
||||||
|
const looseWorldStats = await client.with(z.object({}).passthrough()).call("get_world_stats");
|
||||||
|
if (typeof looseWorldStats.worldAgeDays !== "number") {
|
||||||
|
throw new Error("expected ad-hoc-schema call to still return real world stats data");
|
||||||
|
}
|
||||||
|
console.log("ad-hoc schema call passed through real data:", looseWorldStats.worldAgeDays);
|
||||||
|
|
||||||
|
console.log("== with(schema).call, deliberately wrong shape (expect RconDataBridgeSchemaMismatchError) ==");
|
||||||
|
try {
|
||||||
|
await client.with(z.object({ thisFieldWillNeverExist: z.string() })).call("get_world_stats");
|
||||||
|
throw new Error("expected RconDataBridgeSchemaMismatchError, got a success response");
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof RconDataBridgeSchemaMismatchError)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
console.log(`ad-hoc schema mismatch correctly caught: ${err.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("\nAll smoke checks passed.");
|
||||||
|
} finally {
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error("Smoke test FAILED:", err);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"declaration": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"exactOptionalPropertyTypes": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"]
|
||||||
|
}
|
||||||
Reference in new issue
Block a user