Archived
274 lines
11 KiB
TypeScript
274 lines
11 KiB
TypeScript
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));
|
|
}
|