Structured Komodo port diagnostics + probe button

komodoResolveGamePort silently returned null for six distinct failure
modes (unconfigured, no-name, unreachable, http-error, unparseable,
no-udp-in-response), which made "no game_port — Komodo did not return
one" indistinguishable from an auth failure or an unrecognized response
shape. Adds komodoResolvePortDetailed returning a discriminated union
with the failure reason, HTTP status, and a truncated response snippet.

extractUdpPort broadens to cover four more shapes seen in the wild:
extra host-port field names (HostPort/hostPort/host_port/PublicPort),
`type` as a protocol alias, host-network strings ("28962/udp"), and the
docker-inspect container-keyed form ({ "28960/udp": [{ HostPort }] }).
Arrays reached via a ports-flavored key now win over accidental matches
elsewhere in the tree.

New POST /api/servers/[name]/probe-komodo triggers a fresh lookup,
caches the port on success, and returns the structured result. The RCON
diagnostic panel gains a Probe Komodo button (shown when endpoint is
unresolved and Komodo is configured) that renders the snippet inline —
so unrecognized shapes surface directly instead of vanishing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-09-12 09:21:36 -04:00
co-authored by Claude Opus 4.7
parent 7b4e6e0565
commit 1d05f5df1b
5 changed files with 470 additions and 41 deletions
+187 -41
View File
@@ -80,19 +80,63 @@ export async function komodoRestart(serverName: string): Promise<KomodoRestartRe
return { ok: true };
}
// ---------- Port resolution ----------
export type KomodoPortFailure =
| 'unconfigured'
| 'no-name'
| 'unreachable' // network / DNS / timeout
| 'http-error' // non-2xx
| 'unparseable' // 2xx but body wasn't JSON
| 'no-udp-in-response'; // parsed but no UDP port found
export interface KomodoPortSuccess {
ok: true;
port: number;
snippet: string;
}
export interface KomodoPortFailureResult {
ok: false;
reason: KomodoPortFailure;
detail: string;
httpStatus?: number;
snippet?: string;
}
export type KomodoPortResult = KomodoPortSuccess | KomodoPortFailureResult;
const SNIPPET_LIMIT = 4000;
function truncate(s: string): string {
if (s.length <= SNIPPET_LIMIT) return s;
return s.slice(0, SNIPPET_LIMIT) + `\n… (${s.length - SNIPPET_LIMIT} more bytes)`;
}
function safeJsonStringify(value: unknown): string {
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
/**
* Query Komodo's read API for a server's UDP game port. Called lazily by
* the RCON client and cached into `servers.game_port` on success.
* Detailed variant of `komodoResolveGamePort` — returns a discriminated
* union so callers can distinguish "network died" from "auth failed" from
* "we parsed the JSON but couldn't find a UDP port in a shape we recognize".
*
* Komodo returns full deployment/container state; port mappings live under
* `state.container.ports` on deployments and `state.ports` on stacks/raw
* containers. Shape varies by Komodo version, so we walk a few known
* candidate paths and pick the first UDP entry we can parse.
* On success, the response snippet is included so the caller can render it
* as "here's where we found the port". On no-udp-in-response, the snippet
* is the only way we'll know what shape Komodo actually emitted — surface
* it prominently in the UI so we can extend `extractUdpPort` for that shape.
*/
export async function komodoResolveGamePort(serverName: string): Promise<number | null> {
if (!komodoConfigured()) return null;
export async function komodoResolvePortDetailed(serverName: string): Promise<KomodoPortResult> {
if (!komodoConfigured()) {
return { ok: false, reason: 'unconfigured', detail: 'KOMODO_ADDRESS/KEY/SECRET are not all set' };
}
const row = getServer(serverName);
if (!row?.komodo_name) return null;
if (!row?.komodo_name) {
return { ok: false, reason: 'no-name', detail: `server has no komodo_name: ${serverName}` };
}
const type = row.komodo_type ?? 'deployment';
let path: string;
@@ -104,7 +148,9 @@ export async function komodoResolveGamePort(serverName: string): Promise<number
body = { stack: row.komodo_name };
break;
case 'container':
if (!row.komodo_server) return null;
if (!row.komodo_server) {
return { ok: false, reason: 'no-name', detail: 'container type needs komodo_server' };
}
path = 'read/InspectContainer';
body = { server: row.komodo_server, container: row.komodo_name };
break;
@@ -118,64 +164,164 @@ export async function komodoResolveGamePort(serverName: string): Promise<number
let res: Response;
try {
res = await komodoCall(path, body);
} catch {
return null;
} catch (err) {
return { ok: false, reason: 'unreachable', detail: (err as Error).message };
}
// Read the body up front — we want the snippet even on non-2xx so the
// UI can show what the error page actually said.
const rawText = await res.text().catch(() => '');
if (!res.ok) {
return {
ok: false,
reason: 'http-error',
detail: `HTTP ${res.status} ${res.statusText || ''}`.trim(),
httpStatus: res.status,
snippet: truncate(rawText)
};
}
if (!res.ok) return null;
let json: unknown;
try {
json = await res.json();
} catch {
return null;
json = JSON.parse(rawText);
} catch (err) {
return {
ok: false,
reason: 'unparseable',
detail: `response body is not JSON: ${(err as Error).message}`,
httpStatus: res.status,
snippet: truncate(rawText)
};
}
return extractUdpPort(json);
const port = extractUdpPort(json);
const snippet = truncate(safeJsonStringify(json));
if (port === null) {
return {
ok: false,
reason: 'no-udp-in-response',
detail: 'parsed the response but no UDP port matched any known shape',
httpStatus: res.status,
snippet
};
}
return { ok: true, port, snippet };
}
/**
* Walks a Komodo response looking for a UDP port. Handles the two shapes
* we've seen in the wild:
* Query Komodo's read API for a server's UDP game port. Called lazily by
* the RCON client and cached into `servers.game_port` on success. Thin shim
* over `komodoResolvePortDetailed` that swallows diagnostics — use the
* detailed variant when you care why it failed.
*/
export async function komodoResolveGamePort(serverName: string): Promise<number | null> {
const result = await komodoResolvePortDetailed(serverName);
return result.ok ? result.port : null;
}
// ---------- Extractor ----------
// Property names Komodo/Docker use for the collection of port mappings.
const PORT_ARRAY_KEYS = new Set(['ports', 'Ports', 'port_bindings', 'PortBindings']);
// Value field names for the host-facing port on an object entry.
const HOST_PORT_KEYS = ['published', 'PublishedPort', 'public_port', 'PublicPort', 'HostPort', 'hostPort', 'host_port'];
interface PortsCandidate {
arr: unknown[];
/** True when the array was reached via a `ports`-flavored key — preferred. */
preferred: boolean;
}
/**
* Walks a Komodo response looking for a UDP port. Handles the shapes we've
* seen in the wild:
*
* docker-compose-style: [{ protocol: "udp", published: 4976, target: 28960 }, ...]
* docker-run-style: ["4976:28960/udp", "3074:3074/tcp"]
* docker-compose object: [{ protocol: "udp", published: 4976, target: 28960 }]
* docker-compose caps: [{ Protocol: "udp", PublishedPort: 4976 }]
* docker-run string: ["4976:28960/udp", "3074:3074/tcp"]
* host-network string: ["28962/udp"]
* docker-inspect object: { "28960/udp": [{ "HostIp": "0.0.0.0", "HostPort": "28962" }] }
*
* Returns the first published port whose protocol is UDP.
* Arrays reached via a `ports`/`Ports`/`port_bindings`/`PortBindings` key
* are preferred over arrays discovered elsewhere in the tree, so an
* unrelated array (e.g. tags, labels) can't shadow a real port list.
*/
export function extractUdpPort(payload: unknown): number | null {
const candidates: unknown[] = [];
const candidates: PortsCandidate[] = [];
// Objects whose keys encode `<container-port>/<proto>` — a la docker inspect.
const containerKeyed: Record<string, unknown>[] = [];
const seen = new Set<unknown>();
const walk = (v: unknown): void => {
const walk = (v: unknown, viaPortsKey: boolean): void => {
if (v === null || typeof v !== 'object' || seen.has(v)) return;
seen.add(v);
if (Array.isArray(v)) {
for (const item of v) walk(item);
candidates.push(v);
} else {
for (const val of Object.values(v as Record<string, unknown>)) walk(val);
for (const item of v) walk(item, false);
candidates.push({ arr: v, preferred: viaPortsKey });
return;
}
const obj = v as Record<string, unknown>;
// Detect docker-inspect container-keyed objects: any key like `28960/udp`.
for (const k of Object.keys(obj)) {
if (/^\d+\/(udp|tcp)$/i.test(k)) {
containerKeyed.push(obj);
break;
}
}
for (const [key, val] of Object.entries(obj)) {
walk(val, PORT_ARRAY_KEYS.has(key));
}
};
walk(payload);
walk(payload, false);
// Object-form entries: { protocol, published, target }
for (const arr of candidates) {
for (const entry of arr as unknown[]) {
// Sort so preferred `ports`-keyed arrays win over accidental hits.
candidates.sort((a, b) => (a.preferred === b.preferred ? 0 : a.preferred ? -1 : 1));
// Try object-entry shape first — most Komodo/Docker responses use this.
for (const { arr } of candidates) {
for (const entry of arr) {
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
const e = entry as Record<string, unknown>;
const proto = String(e.protocol ?? e.Protocol ?? '').toLowerCase();
const proto = String(e.protocol ?? e.Protocol ?? e.type ?? e.Type ?? '').toLowerCase();
if (proto !== 'udp') continue;
const raw = e.published ?? e.PublishedPort ?? e.public_port ?? e.HostPort ?? e.host_port;
const num = typeof raw === 'string' ? Number.parseInt(raw, 10) : Number(raw);
if (Number.isFinite(num) && num > 0) return num;
for (const field of HOST_PORT_KEYS) {
const raw = e[field];
if (raw === undefined || raw === null) continue;
const num = typeof raw === 'string' ? Number.parseInt(raw, 10) : Number(raw);
if (Number.isFinite(num) && num > 0) return num;
}
}
}
}
// String-form entries: "4976:28960/udp"
for (const arr of candidates) {
for (const entry of arr as unknown[]) {
// Then string shapes: "host:container/udp" or "container/udp" (host-net).
for (const { arr } of candidates) {
for (const entry of arr) {
if (typeof entry !== 'string') continue;
const m = /^(\d+):\d+\/udp$/i.exec(entry);
if (m) return Number.parseInt(m[1], 10);
const hostMapped = /^(\d+):\d+\/udp$/i.exec(entry);
if (hostMapped) return Number.parseInt(hostMapped[1], 10);
const hostNet = /^(\d+)\/udp$/i.exec(entry);
if (hostNet) return Number.parseInt(hostNet[1], 10);
}
}
// Finally, docker-inspect container-keyed shape:
// { "28960/udp": [{ HostIp, HostPort }] }
for (const obj of containerKeyed) {
for (const [key, val] of Object.entries(obj)) {
if (!/^\d+\/udp$/i.test(key)) continue;
if (!Array.isArray(val)) continue;
for (const binding of val) {
if (!binding || typeof binding !== 'object') continue;
const b = binding as Record<string, unknown>;
for (const field of HOST_PORT_KEYS) {
const raw = b[field];
if (raw === undefined || raw === null) continue;
const num = typeof raw === 'string' ? Number.parseInt(raw, 10) : Number(raw);
if (Number.isFinite(num) && num > 0) return num;
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
export type KomodoPortFailure =
| 'unconfigured'
| 'no-name'
| 'unreachable'
| 'http-error'
| 'unparseable'
| 'no-udp-in-response';
/** Short fix hint per failure reason, shown under the Komodo probe result. */
export function komodoFixHint(reason: KomodoPortFailure, httpStatus?: number): string {
switch (reason) {
case 'unconfigured':
return 'Set KOMODO_ADDRESS, KOMODO_API_KEY, and KOMODO_API_SECRET in the container env.';
case 'no-name':
return 'This server row has no komodo_name — set it via SQL or via the fleet config.';
case 'unreachable':
return 'Network, DNS, or timeout. Check that KOMODO_ADDRESS is reachable from this container.';
case 'http-error':
if (httpStatus === 401 || httpStatus === 403) return 'Auth rejected — verify KOMODO_API_KEY and KOMODO_API_SECRET.';
if (httpStatus === 404) return 'Endpoint or deployment not found — check komodo_name matches the Komodo UI exactly.';
return `Komodo returned ${httpStatus ?? 'an error'}. Check the endpoint path and credentials.`;
case 'unparseable':
return 'Response was not JSON — is KOMODO_ADDRESS pointing at the Core API (not the Periphery)?';
case 'no-udp-in-response':
return 'Parsed the response but no UDP port matched our known shapes. See the snippet below and extend extractUdpPort.';
}
}