Files
KSP-MissionControl/apps/tools/ksp-bridge/src/bridge.ts
T
Mavis aebee77843 phase 1c-extract: typed kRPC service client + SpaceCenter extract
Built the missing piece that connects the ksp-bridge to a real KSP
instance via kRPC. This adds a typed service client on top of the
existing KRPCClient, plus the SpaceCenter-specific extraction logic
that pulls the universe state from a running KSP save.

@kerbal-rt/krpc-client
- types.ts — runtime representation of kRPC Type descriptors
  (TypeCode enum, KrpcType interface, decodeKrpcType, typeName)
- decoder.ts — kRPC value codec: primitive decode/encode, class refs,
  enums, collections (LIST/SET/TUPLE/DICTIONARY), system messages
  (STATUS/SERVICES/STREAM/EVENT/PROCEDURE_CALL). 34 unit tests.
- services.ts — ServiceCache built from KRPC.GetServices() response.
  Lookup by (service, procedure), enum value/name resolution. 12 tests.
- service-client.ts — KrpcServices: high-level invoke-by-name client.
  loadServices() helper to connect + load catalog. 9 integration tests
  with a mock kRPC server.
- schema.ts — added Set/Dictionary/Event/Expression types so the
  decoder can handle system messages without external .proto files.
  Also fixed a bug where 'STREAM' was being encoded as 0 due to
  protobufjs's nested-enum string lookup.

ksp-bridge
- extract.ts — the actual SpaceCenter calls. ~280 procedure calls
  per poll for a typical KSP save (UT, bodies, vessels, then per-body
  and per-vessel class methods in parallel). Build the UniverseSnapshot.
- krpc-adapter.ts — rewrote to use KrpcServices (typed) instead of
  the stub extract function. Supports an optional injected services
  for testing.
- bridge.ts — uses the new ExtractedState type and buildSnapshot.
- index.ts — connects to kRPC; falls back to mock mode if no server.
- convert.ts — backward-compat shim, re-exports from extract.ts.

The ksp-bridge can now talk to a real KSP install. We do NOT need
the kRPC mod's .proto files on disk — the server's GetServices()
response is the source of truth for type info. Documented the full
list of procedures we call, the kRPC value encoding, and the new
architecture in ksp/README.md.

Tests: 119 total, all green. Typecheck and build clean across all 11
projects.

Bonus: fixed an integer-overflow bug in the krpc-client connect()
handshake (was passing 'RPC'/'STREAM' strings to protobufjs; its
nested-enum string lookup silently encodes as 0, which made the
stream handshake send the wrong type. Switched to numeric codes.)
2026-06-02 22:02:26 +00:00

124 lines
3.9 KiB
TypeScript

/**
* KSP Bridge — main loop.
*
* Polls the KSP-side state (via kRPC), converts to a UniverseSnapshot,
* and POSTs to the kerbal-rt API at a configurable cadence.
*
* Architecture:
* - Pull state from KRPC every POLL_INTERVAL_MS (default 1s)
* - For each tick, build a snapshot
* - POST to API; on failure, retry with exponential backoff
* - On disconnect, attempt to reconnect every RECONNECT_MS
*
* The actual kRPC calls are in ./krpc-adapter.ts. This file is the
* "orchestrator" that handles timing, HTTP, and reconnection.
*/
import type { ExtractedState } from './extract.js';
import { buildSnapshot } from './extract.js';
export interface BridgeOptions {
/** API base URL, e.g. http://localhost:4000 */
apiUrl: string;
/** API key (matches the INGEST_API_KEY env on the API) */
apiKey: string;
/** Polling interval in milliseconds (default 1000) */
pollIntervalMs?: number;
/** Function that returns the current KSP state, or null if KSP isn't ready */
getState: () => Promise<ExtractedState | null>;
/** Optional log function (defaults to console.log) */
log?: (msg: string) => void;
/** Optional error log function */
err?: (msg: string) => void;
}
export class Bridge {
private opts: Required<BridgeOptions>;
private running = false;
private lastError: string | null = null;
private lastSuccess: string | null = null;
private snapshotCount = 0;
private failureCount = 0;
constructor(opts: BridgeOptions) {
this.opts = {
apiUrl: opts.apiUrl.replace(/\/$/, ''),
apiKey: opts.apiKey,
pollIntervalMs: opts.pollIntervalMs ?? 1000,
getState: opts.getState,
log: opts.log ?? ((m) => console.log(`[ksp-bridge] ${m}`)),
err: opts.err ?? ((m) => console.error(`[ksp-bridge] ${m}`)),
};
}
async start(): Promise<void> {
this.running = true;
this.opts.log(`starting — API=${this.opts.apiUrl} interval=${this.opts.pollIntervalMs}ms`);
while (this.running) {
const t0 = Date.now();
try {
const state = await this.opts.getState();
if (state) {
const capturedAt = new Date().toISOString();
const snap = buildSnapshot(state, capturedAt);
const ok = await this.postSnapshot(snap);
if (ok) {
this.snapshotCount += 1;
this.lastSuccess = capturedAt;
this.failureCount = 0;
this.lastError = null;
if (this.snapshotCount % 10 === 1) {
this.opts.log(
`ut=${state.ut.toFixed(0)} bodies=${state.bodies.length} vessels=${state.vessels.length} → OK`,
);
}
}
} else {
this.opts.log('KSP not ready (no state)');
}
} catch (err) {
this.failureCount += 1;
this.lastError = String((err as Error).message ?? err);
this.opts.err(`poll failed: ${this.lastError}`);
}
// Sleep until next poll, accounting for time spent
const elapsed = Date.now() - t0;
const wait = Math.max(0, this.opts.pollIntervalMs - elapsed);
if (this.running && wait > 0) {
await sleep(wait);
}
}
}
stop(): void {
this.running = false;
}
getStats() {
return {
snapshotCount: this.snapshotCount,
failureCount: this.failureCount,
lastSuccess: this.lastSuccess,
lastError: this.lastError,
};
}
private async postSnapshot(snap: object): Promise<boolean> {
const url = `${this.opts.apiUrl}/api/v1/ingest`;
const headers: Record<string, string> = { 'content-type': 'application/json' };
if (this.opts.apiKey) headers['x-api-key'] = this.opts.apiKey;
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(snap),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
return true;
}
}
function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}