rpc-bastion 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/data/args.ts","../src/cli.ts","../src/data/doctor.ts","../src/data/config.ts","../src/data/monitor.ts","../src/data/simulate.ts","../src/data/watch-tx.ts","../src/ui/run.ts","../src/ui/ansi.ts","../src/ui/render.ts","../src/ui/bin.ts"],"names":["systemClock","createEventBus","createMockRpcServer","createResilientRpc","createChaosTransport","createConfirmationEngine","readFileSync","createSolanaRpc","asSenderRpc","createSolanaRpcSubscriptions","parseArgs","route"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,IAAA,YAAA,GAAA,EAAA;AAAA,QAAA,CAAA,YAAA,EAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,OAAA,EAAA,MAAA,OAAA;AAAA,EAAA,UAAA,EAAA,MAAA,UAAA;AAAA,EAAA,SAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAcO,SAAS,UAAU,IAAA,EAAqC;AAC7D,EAAA,MAAM,QAA0C,EAAC;AACjD,EAAA,MAAM,cAAwB,EAAC;AAC/B,EAAA,IAAI,OAAA,GAAyB,IAAA;AAE7B,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AACpC,IAAA,MAAM,GAAA,GAAM,KAAK,CAAC,CAAA;AAClB,IAAA,IAAI,GAAA,CAAI,UAAA,CAAW,IAAI,CAAA,EAAG;AACxB,MAAA,MAAM,IAAA,GAAO,GAAA,CAAI,KAAA,CAAM,CAAC,CAAA;AACxB,MAAA,MAAM,EAAA,GAAK,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC3B,MAAA,IAAI,MAAM,CAAA,EAAG;AACX,QAAA,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,EAAG,EAAE,CAAC,CAAA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AAI,CAAA;AAC3B,QAAA;AAAA,MACF,KAAK,SAAA;AACH,QAAA,MAAM,kBAAkB,IAAI,CAAA;AAC5B,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,MAAM,kBAAkB,IAAI,CAAA;AAC5B,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,MAAM,mBAAmB,IAAI,CAAA;AAC7B,QAAA;AAAA,MACF;AACE,QAAA,OAAA,EAAQ;AAAA;AAEZ,IAAA,OAAO,CAAA;AAAA,EACT,SAAS,CAAA,EAAG;AACV,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAY,CAAA,YAAa,KAAA,GAAQ,EAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA,CAAE,CAAA;AACtE,IAAA,OAAO,CAAA;AAAA,EACT;AACF;;;AGtNA,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,EAC1B,CAAC,IAAA,KAAS;AACR,IAAA,OAAA,CAAQ,QAAA,GAAW,IAAA;AAAA,EACrB,CAAA;AAAA,EACA,CAAC,GAAA,KAAQ;AACP,IAAA,OAAA,CAAQ,MAAM,GAAG,CAAA;AACjB,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA","file":"bin.cjs","sourcesContent":["/** A parsed command line: the command, positional args, and flags. */\nexport interface ParsedArgs {\n command: string | null;\n positionals: string[];\n /** `--flag value` and `--bool` (→ `true`). */\n flags: Record<string, string | boolean>;\n}\n\n/**\n * A tiny, dependency-free argv parser. `--key value` → `{ key: 'value' }`;\n * `--key=value` → same; a bare `--flag` (followed by another flag or nothing) →\n * `{ flag: true }`. The first non-flag token is the command; the rest are\n * positionals. Pure and fully testable.\n */\nexport function parseArgs(argv: readonly string[]): ParsedArgs {\n const flags: Record<string, string | boolean> = {};\n const positionals: string[] = [];\n let command: string | null = null;\n\n for (let i = 0; i < argv.length; i++) {\n const tok = argv[i]!;\n if (tok.startsWith('--')) {\n const body = tok.slice(2);\n const eq = body.indexOf('=');\n if (eq >= 0) {\n flags[body.slice(0, eq)] = body.slice(eq + 1);\n } else {\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith('--')) {\n flags[body] = next;\n i++;\n } else {\n flags[body] = true;\n }\n }\n } else if (command === null) {\n command = tok;\n } else {\n positionals.push(tok);\n }\n }\n\n return { command, positionals, flags };\n}\n\n/** Reads a flag as a string, or returns `undefined`. */\nexport function flagString(args: ParsedArgs, name: string): string | undefined {\n const v = args.flags[name];\n return typeof v === 'string' ? v : undefined;\n}\n\n/** Reads a flag as a boolean (presence or `true`). */\nexport function flagBool(args: ParsedArgs, name: string): boolean {\n return args.flags[name] === true || args.flags[name] === 'true';\n}\n\n/** Reads a flag as a positive integer, or `fallback`. */\nexport function flagInt(args: ParsedArgs, name: string, fallback: number): number {\n const v = args.flags[name];\n if (typeof v !== 'string') return fallback;\n const n = Number.parseInt(v, 10);\n return Number.isFinite(n) && n > 0 ? n : fallback;\n}\n","import type { ParsedArgs } from './data/args';\n\n/** The set of known commands. */\nexport const COMMANDS = ['doctor', 'monitor', 'watch-tx', 'simulate', 'help'] as const;\nexport type Command = (typeof COMMANDS)[number];\n\n/**\n * Resolves the command to run from parsed args. Pure + fully tested — this is the\n * routing brain; the live `main()` (which does I/O) lives in `./ui/run`.\n */\nexport function route(args: ParsedArgs): Command {\n if (args.flags['help'] === true || args.flags['version'] === true) return 'help';\n const c = args.command;\n if (c && (COMMANDS as readonly string[]).includes(c)) return c as Command;\n return 'help';\n}\n","import { systemClock } from '@rpc-bastion/core';\n\n/** The doctor only reads time; a `now()` source is all it needs. */\nexport type DoctorClock = { now(): number };\n\n/** The minimal per-endpoint RPC surface `doctor` probes. */\nexport interface DoctorRpc {\n getSlot(config?: Record<string, unknown>): { send(opts?: { abortSignal?: AbortSignal }): Promise<bigint> };\n getHealth(config?: Record<string, unknown>): { send(opts?: { abortSignal?: AbortSignal }): Promise<string> };\n getVersion(config?: Record<string, unknown>): {\n send(opts?: { abortSignal?: AbortSignal }): Promise<{ 'solana-core'?: string; 'feature-set'?: number }>;\n };\n}\n\n/** Builds a {@link DoctorRpc} for an endpoint URL. */\nexport type DoctorRpcFactory = (url: string) => DoctorRpc;\n\n/** Per-endpoint diagnostic result. */\nexport interface EndpointDiagnostic {\n url: string;\n /** `true` if the endpoint answered every probe. */\n reachable: boolean;\n /** Median latency over the probes (ms), or null if unreachable. */\n latencyP50Ms: number | null;\n /** `getHealth` result (`ok` / a behind message), or null. */\n health: string | null;\n /** Latest slot seen, or null. */\n slot: bigint | null;\n /** Slots behind the freshest endpoint in this run, or null. */\n slotLag: number | null;\n /** `solana-core` version, or null. */\n version: string | null;\n /** First error message, if any probe failed. */\n error: string | null;\n}\n\n/** The full doctor report (the `--json` payload). */\nexport interface DoctorReport {\n endpoints: EndpointDiagnostic[];\n /** Freshest slot across reachable endpoints, or null. */\n clusterMaxSlot: bigint | null;\n /** Count reachable / total. */\n reachable: number;\n total: number;\n}\n\n/** Options for {@link runDoctor}. */\nexport interface DoctorOptions {\n /** Latency probes per endpoint (default 5). */\n probes?: number;\n rpcFactory: DoctorRpcFactory;\n clock?: DoctorClock;\n signal?: AbortSignal;\n}\n\n/** Median of a numeric array (linear interpolation not needed for ms). */\nexport function median(values: readonly number[]): number | null {\n if (values.length === 0) return null;\n const sorted = [...values].sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;\n}\n\n/**\n * Turns a probe failure into a human-readable message.\n *\n * Works around an upstream Solana Kit defect: when an endpoint answers HTTP 200\n * with a JSON-RPC *error* whose code Kit's message template can't render (e.g. a\n * keyless gateway returning `-32000 \"needs an API key\"`), Kit's own formatter\n * (`@solana/errors` → `getHumanReadableErrorMessage`, reached via\n * `getSolanaErrorFromJsonRpcError` → `new SolanaError`) throws a bare\n * `TypeError: Cannot read properties of undefined (reading 'length')` *instead of*\n * the intended SolanaError. That TypeError carries no `context`/`code`, so the\n * real RPC message is unrecoverable — but its stack unambiguously identifies the\n * cause. Detect that signature and report something actionable rather than leaking\n * Kit's internal failure.\n */\nexport function describeProbeError(e: unknown): string {\n if (e instanceof TypeError) {\n const stack = e.stack ?? '';\n if (\n stack.includes('getHumanReadableErrorMessage') ||\n stack.includes('getSolanaErrorFromJsonRpcError') ||\n stack.includes('@solana/errors')\n ) {\n return 'endpoint returned a JSON-RPC error Solana Kit could not format (often a keyless/unauthorized gateway requiring an API key)';\n }\n }\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Probes a single endpoint: `probes` latency-timed `getSlot` calls (p50), one\n * `getHealth`, and one `getVersion`. Never throws — failures are captured in the\n * returned diagnostic. Pure given an injected `rpcFactory` + `clock`.\n */\nexport async function probeEndpoint(\n url: string,\n options: { probes: number; rpc: DoctorRpc; clock: DoctorClock; signal?: AbortSignal },\n): Promise<EndpointDiagnostic> {\n const { probes, rpc, clock, signal } = options;\n const latencies: number[] = [];\n let slot: bigint | null = null;\n let error: string | null = null;\n\n for (let i = 0; i < probes; i++) {\n const start = clock.now();\n try {\n const s = await rpc.getSlot().send(signal ? { abortSignal: signal } : undefined);\n latencies.push(clock.now() - start);\n slot = s;\n } catch (e) {\n error ??= describeProbeError(e);\n }\n }\n\n let health: string | null = null;\n let version: string | null = null;\n if (latencies.length > 0) {\n try {\n health = await rpc.getHealth().send(signal ? { abortSignal: signal } : undefined);\n } catch (e) {\n error ??= describeProbeError(e);\n }\n try {\n const v = await rpc.getVersion().send(signal ? { abortSignal: signal } : undefined);\n version = v['solana-core'] ?? null;\n } catch (e) {\n error ??= describeProbeError(e);\n }\n }\n\n const reachable = latencies.length > 0;\n return {\n url,\n reachable,\n latencyP50Ms: median(latencies),\n health,\n slot,\n slotLag: null, // filled in once the cluster max is known\n version,\n error,\n };\n}\n\n/**\n * Runs `doctor` across all endpoints: probes each (in parallel), computes the\n * cluster-max slot, and back-fills each endpoint's `slotLag`. Pure given the\n * injected `rpcFactory`/`clock` — the rendering layer formats the result.\n */\nexport async function runDoctor(urls: readonly string[], options: DoctorOptions): Promise<DoctorReport> {\n const probes = options.probes ?? 5;\n const clock = options.clock ?? systemClock;\n\n const diagnostics = await Promise.all(\n urls.map((url) =>\n probeEndpoint(url, {\n probes,\n rpc: options.rpcFactory(url),\n clock,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n ),\n );\n\n let clusterMaxSlot: bigint | null = null;\n for (const d of diagnostics) {\n if (d.slot !== null && (clusterMaxSlot === null || d.slot > clusterMaxSlot)) clusterMaxSlot = d.slot;\n }\n for (const d of diagnostics) {\n d.slotLag = d.slot !== null && clusterMaxSlot !== null ? Number(clusterMaxSlot - d.slot) : null;\n }\n\n const reachable = diagnostics.filter((d) => d.reachable).length;\n return { endpoints: diagnostics, clusterMaxSlot, reachable, total: urls.length };\n}\n\n/** Serializes a {@link DoctorReport} to stable JSON (bigint → string). */\nexport function doctorReportToJson(report: DoctorReport): string {\n return JSON.stringify(\n report,\n (_key, value) => (typeof value === 'bigint' ? value.toString() : value),\n 2,\n );\n}\n","/** The `bastion.config.json` shape. */\nexport interface BastionConfig {\n endpoints: string[];\n jito?: { region?: string; baseUrl?: string };\n}\n\n/**\n * Parses + validates a `bastion.config.json` payload. Pure (takes the already-read\n * text) so it's testable without filesystem access. Throws a clear error on a\n * malformed config.\n */\nexport function parseConfig(text: string): BastionConfig {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (e) {\n throw new Error(`invalid bastion.config.json: ${e instanceof Error ? e.message : String(e)}`);\n }\n if (typeof raw !== 'object' || raw === null) throw new Error('bastion.config.json must be an object');\n const endpoints = (raw as { endpoints?: unknown }).endpoints;\n if (!Array.isArray(endpoints) || endpoints.length === 0 || !endpoints.every((e) => typeof e === 'string')) {\n throw new Error('bastion.config.json must have a non-empty \"endpoints\" string array');\n }\n const jito = (raw as { jito?: unknown }).jito;\n const config: BastionConfig = { endpoints: endpoints as string[] };\n if (jito && typeof jito === 'object') {\n const j = jito as { region?: unknown; baseUrl?: unknown };\n config.jito = {\n ...(typeof j.region === 'string' ? { region: j.region } : {}),\n ...(typeof j.baseUrl === 'string' ? { baseUrl: j.baseUrl } : {}),\n };\n }\n return config;\n}\n\n/**\n * Resolves endpoints from either `--endpoints` (comma-separated) or a parsed\n * config. `--endpoints` wins when both are present.\n */\nexport function resolveEndpoints(opts: { endpoints?: string; config?: BastionConfig }): string[] {\n if (opts.endpoints) {\n const list = opts.endpoints\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (list.length === 0) throw new Error('--endpoints provided but empty');\n return list;\n }\n if (opts.config) return opts.config.endpoints;\n throw new Error('no endpoints: pass --endpoints <urls> or --config <bastion.config.json>');\n}\n","import type { BreakerState, EndpointHealth } from '@rpc-bastion/core';\n\n/** A formatted row for the monitor table (pure projection of EndpointHealth). */\nexport interface MonitorRow {\n url: string;\n /** Status dot category. */\n dot: 'green' | 'yellow' | 'red';\n latencyMs: number;\n errorRatePct: number;\n slotLag: number | null;\n breaker: BreakerState;\n inFlight: number;\n}\n\n/** A summary across the whole pool. */\nexport interface MonitorSummary {\n rows: MonitorRow[];\n healthy: number;\n total: number;\n /** Worst (highest) slot lag across endpoints, or null. */\n maxSlotLag: number | null;\n}\n\n/** Categorizes an endpoint into a status dot from its health + breaker. */\nexport function statusDot(health: EndpointHealth): MonitorRow['dot'] {\n if (health.breaker === 'open' || health.status === 'broken') return 'red';\n if (health.breaker === 'half-open' || health.status === 'degraded' || health.errorRate > 0.1 || (health.slotLag ?? 0) > 50)\n return 'yellow';\n return 'green';\n}\n\n/**\n * Projects a pool health snapshot into renderable monitor rows + a summary.\n * Pure — the rendering layer turns this into a table/sparkline. Reuses the same\n * `EndpointHealth` the SDK pool produces (no parallel health model).\n */\nexport function summarizeSnapshot(snapshot: readonly EndpointHealth[]): MonitorSummary {\n const rows: MonitorRow[] = snapshot.map((h) => ({\n url: h.url,\n dot: statusDot(h),\n latencyMs: Math.round(h.latencyEwmaMs),\n errorRatePct: Math.round(h.errorRate * 100),\n slotLag: h.slotLag,\n breaker: h.breaker,\n inFlight: h.inFlight,\n }));\n\n const healthy = rows.filter((r) => r.dot === 'green').length;\n let maxSlotLag: number | null = null;\n for (const r of rows) {\n if (r.slotLag !== null && (maxSlotLag === null || r.slotLag > maxSlotLag)) maxSlotLag = r.slotLag;\n }\n return { rows, healthy, total: rows.length, maxSlotLag };\n}\n\n/**\n * Appends a latency sample to a bounded ring buffer (for the monitor sparkline).\n * Returns a NEW array (immutable), keeping at most `size` samples.\n */\nexport function pushSample(history: readonly number[], sample: number, size = 30): number[] {\n const next = [...history, sample];\n return next.length > size ? next.slice(next.length - size) : next;\n}\n","import {\n createEventBus,\n createResilientRpc,\n type BastionEvent,\n type CircuitBreakerOptions,\n type EndpointHealth,\n type LoadBalancerStrategy,\n} from '@rpc-bastion/core';\nimport { createChaosTransport, createMockRpcServer, type ChaosPlan } from '@rpc-bastion/testkit';\n\n/** A named, scripted chaos scenario for `bastion simulate`. */\nexport interface Scenario {\n name: string;\n description: string;\n endpoints: string[];\n /** Per-endpoint chaos plan, keyed by endpoint url. */\n plans: Record<string, ChaosPlan>;\n /** How many probe ticks to run (default 10). */\n ticks: number;\n /** Load-balancer strategy (default the pool's `health-weighted`). */\n strategy?: LoadBalancerStrategy;\n /**\n * User-level calls issued per tick (default 1). A small burst lets a failing\n * endpoint accumulate enough failures to trip its breaker — the drama beat.\n */\n callsPerTick?: number;\n /** Per-scenario breaker tuning, so a scenario can show open → half-open → closed. */\n breaker?: CircuitBreakerOptions;\n}\n\n/** A narrative event observed during one tick, projected from the bus. */\nexport interface TickEvent {\n /** Compact kind for the renderer to colour: which arc beat this is. */\n kind: 'served' | 'error' | 'failover' | 'breaker-open' | 'breaker-half-open' | 'breaker-closed';\n /** The endpoint this event is about (the `to` endpoint for a failover). */\n endpoint: string;\n /** A short human label, e.g. `rpc-a → rpc-b` or `OPEN`. */\n detail: string;\n}\n\n/** A single tick of a simulation: the health snapshot after the tick's probe. */\nexport interface SimulationTick {\n tick: number;\n snapshot: EndpointHealth[];\n /**\n * The endpoint that ultimately served this tick's user-level call, or null if\n * the call failed on every survivor. Drives the per-endpoint traffic counters.\n */\n servedBy?: string | null;\n /** `false` only when the user-level call threw after all failover/retry. */\n userCallOk?: boolean;\n /** Narrative events the bus emitted during this tick (failover, breaker flips). */\n events?: TickEvent[];\n}\n\n/** The aggregate verdict of a simulation run — the \"0 failed user calls\" thesis. */\nexport interface SimulationSummary {\n /** Every tick is one user-level call. */\n userCallsTotal: number;\n /** Calls that threw after all failover + retry were exhausted. */\n userCallsFailed: number;\n /** Per-endpoint served count + error count over the run. */\n perEndpoint: Array<{ url: string; served: number; errors: number }>;\n /** Count of breaker open transitions observed. */\n breakerOpens: number;\n}\n\n/** The built-in scenario catalogue. */\nexport const SCENARIOS: Record<string, Scenario> = {\n 'live-outage': {\n name: 'live-outage',\n description:\n 'The movie: 3 healthy endpoints → the primary blacks out (breaker opens, traffic reroutes) → it recovers (half-open trial → closed). Zero failed user calls.',\n endpoints: ['rpc-a', 'rpc-b', 'rpc-c'],\n plans: {\n // Healthy (mild latency) → total blackout from 1.5s → recovery from 4s.\n 'rpc-a': [\n { atMs: 0, set: { latency: { minMs: 18, maxMs: 45 } } },\n { atMs: 1_500, set: { dropRate: 1 } },\n { atMs: 4_000, set: { dropRate: 0, latency: { minMs: 22, maxMs: 50 } } },\n ],\n 'rpc-b': [{ atMs: 0, set: { latency: { minMs: 25, maxMs: 70 } } }],\n 'rpc-c': [{ atMs: 0, set: { latency: { minMs: 30, maxMs: 85 } } }],\n },\n ticks: 14,\n // Round-robin keeps probing rpc-a during the outage so its failures pile up\n // and the breaker actually opens; the burst gets there within one tick.\n strategy: 'round-robin',\n callsPerTick: 3,\n breaker: { failureThreshold: 3, windowMs: 5_000, cooldownMs: 1_000 },\n },\n 'flaky-endpoint': {\n name: 'flaky-endpoint',\n description: 'One endpoint degrades (latency + 500s) mid-run; the pool routes away from it.',\n endpoints: ['rpc-a', 'rpc-b'],\n plans: {\n 'rpc-a': [\n { atMs: 0, set: {} },\n { atMs: 2_000, set: { latency: { minMs: 400, maxMs: 800 }, errorRate: { http500: 0.5 } } },\n ],\n 'rpc-b': [],\n },\n ticks: 10,\n },\n 'cascading-failure': {\n name: 'cascading-failure',\n description: 'Endpoints fail one after another; the breaker opens and probes recover them.',\n endpoints: ['rpc-a', 'rpc-b', 'rpc-c'],\n plans: {\n 'rpc-a': [{ atMs: 1_000, set: { dropRate: 1 } }],\n 'rpc-b': [{ atMs: 3_000, set: { dropRate: 1 } }],\n 'rpc-c': [],\n },\n ticks: 12,\n },\n 'rate-limited': {\n name: 'rate-limited',\n description: 'All endpoints throw 429s intermittently; retries with backoff absorb them.',\n endpoints: ['rpc-a', 'rpc-b'],\n plans: {\n 'rpc-a': [{ atMs: 0, set: { errorRate: { http429: 0.4 } } }],\n 'rpc-b': [{ atMs: 0, set: { errorRate: { http429: 0.4 } } }],\n },\n ticks: 10,\n },\n};\n\n/** Lists the available scenario names + descriptions. */\nexport function listScenarios(): Array<{ name: string; description: string }> {\n return Object.values(SCENARIOS).map((s) => ({ name: s.name, description: s.description }));\n}\n\n/** Options for {@link runSimulation}. */\nexport interface SimulationOptions {\n /** Advances the simulated clock + mock chain by this many ms per tick (default 500). */\n tickMs?: number;\n seed?: number;\n /** Called after each tick (for live rendering). */\n onTick?: (tick: SimulationTick) => void;\n /** Drives time + the mock chain forward between ticks (injected for tests). */\n advance: (ms: number) => Promise<void> | void;\n /** Reads \"now\" in ms (injected; defaults to a tick-counted clock). */\n now: () => number;\n}\n\n/**\n * Runs a named scenario against a resilient pool built over chaos transports\n * (real SDK pool/health code), returning a snapshot per tick. The caller injects\n * `advance`/`now` so tests drive it deterministically with fake timers + a\n * ManualClock; the renderer just consumes the ticks.\n */\nexport async function runSimulation(scenario: Scenario, options: SimulationOptions): Promise<SimulationTick[]> {\n const tickMs = options.tickMs ?? 500;\n const clock = { now: options.now, sleep: async () => undefined };\n\n // A bus so each tick can show the real failover/breaker events the stack emits.\n const bus = createEventBus();\n\n // A chaos transport per endpoint, fed by a shared mock chain.\n const server = createMockRpcServer({ slot: 1000, blockHeight: 1000 });\n const { pool, rpc } = createResilientRpc(\n scenario.endpoints.map((url) => ({ url })),\n {\n bus,\n clock,\n ...(scenario.strategy ? { strategy: scenario.strategy } : {}),\n ...(scenario.breaker ? { breaker: scenario.breaker } : {}),\n pool: {\n probe: { enabled: false },\n transportFactory: (config: { url: string }) =>\n createChaosTransport(server.transport, {\n plan: scenario.plans[config.url] ?? [],\n endpointId: config.url,\n clock,\n seed: options.seed ?? 42,\n }),\n },\n },\n );\n\n // Collect this tick's narrative events; the loop drains + clears it each tick.\n let pending: TickEvent[] = [];\n let lastServed: string | null = null;\n bus.onAny((event: BastionEvent) => {\n switch (event.type) {\n case 'rpc.response':\n if (event.ok) {\n lastServed = event.endpoint;\n pending.push({ kind: 'served', endpoint: event.endpoint, detail: `${Math.round(event.latencyMs)}ms` });\n }\n break;\n case 'rpc.error':\n pending.push({ kind: 'error', endpoint: event.endpoint, detail: event.errorClass });\n break;\n case 'rpc.failover':\n if (event.to) pending.push({ kind: 'failover', endpoint: event.to, detail: `${event.from} → ${event.to}` });\n break;\n case 'breaker.state':\n pending.push({\n kind:\n event.state === 'open'\n ? 'breaker-open'\n : event.state === 'half-open'\n ? 'breaker-half-open'\n : 'breaker-closed',\n endpoint: event.endpoint,\n detail: event.state.toUpperCase(),\n });\n break;\n default:\n break;\n }\n });\n\n const callsPerTick = Math.max(1, scenario.callsPerTick ?? 1);\n const ticks: SimulationTick[] = [];\n for (let i = 0; i < scenario.ticks; i++) {\n pending = [];\n lastServed = null;\n let userCallOk = true;\n // A small burst of user-level calls per tick through the resilient pool\n // (exercises balancer/failover/breaker/retry). A user call only fails if\n // every survivor is down for that call — the thesis is that never happens.\n for (let c = 0; c < callsPerTick; c++) {\n try {\n await rpc.getSlot().send();\n } catch {\n userCallOk = false;\n }\n }\n const snapshot = pool.getHealthSnapshot();\n const tick: SimulationTick = {\n tick: i,\n snapshot,\n servedBy: userCallOk ? lastServed : null,\n userCallOk,\n events: pending,\n };\n ticks.push(tick);\n options.onTick?.(tick);\n await options.advance(tickMs);\n }\n return ticks;\n}\n\n/**\n * Projects a finished run into the headline verdict: how many user-level calls\n * the SDK made, how many failed despite failover/retry (the thesis is **zero**),\n * per-endpoint traffic, and how many times a breaker opened. Pure over the ticks.\n */\nexport function summarizeSimulation(ticks: readonly SimulationTick[]): SimulationSummary {\n const perEndpoint = new Map<string, { url: string; served: number; errors: number }>();\n const ensure = (url: string) => {\n let row = perEndpoint.get(url);\n if (!row) {\n row = { url, served: 0, errors: 0 };\n perEndpoint.set(url, row);\n }\n return row;\n };\n\n let userCallsFailed = 0;\n let breakerOpens = 0;\n for (const tick of ticks) {\n if (tick.userCallOk === false) userCallsFailed++;\n if (tick.servedBy) ensure(tick.servedBy).served++;\n for (const ev of tick.events ?? []) {\n if (ev.kind === 'error') ensure(ev.endpoint).errors++;\n if (ev.kind === 'breaker-open') breakerOpens++;\n }\n }\n\n return {\n userCallsTotal: ticks.length,\n userCallsFailed,\n perEndpoint: [...perEndpoint.values()],\n breakerOpens,\n };\n}\n","import {\n createConfirmationEngine,\n type ConfirmationOutcome,\n type Commitment,\n type SenderRpc,\n} from '@rpc-bastion/sender';\nimport type { Clock, RpcSubscriptionsApiLike } from '@rpc-bastion/core';\n\n/** A point-in-time status line for the `watch-tx` UI. */\nexport interface WatchTxUpdate {\n at: number;\n state: 'watching' | 'confirmed' | 'failed' | 'expired' | 'aborted';\n detail: string;\n}\n\n/** Final result of watching a transaction. */\nexport interface WatchTxResult {\n signature: string;\n outcome: ConfirmationOutcome['type'];\n slot: bigint | null;\n updates: WatchTxUpdate[];\n}\n\n/** Options for {@link watchTransaction}. */\nexport interface WatchTxOptions {\n rpc: SenderRpc;\n rpcSubscriptions?: RpcSubscriptionsApiLike;\n lastValidBlockHeight: bigint;\n commitment?: Commitment;\n clock?: Clock;\n pollIntervalMs?: number;\n blockHeightIntervalMs?: number;\n signal?: AbortSignal;\n /** Called on each status update (for live rendering). */\n onUpdate?: (update: WatchTxUpdate) => void;\n}\n\n/**\n * Watches a transaction signature to a terminal state, reusing the SDK's\n * confirmation engine (WS + polling race). Returns the outcome plus a timeline of\n * updates. Pure given injected `rpc`/`clock` — no rendering here.\n */\nexport async function watchTransaction(signature: string, options: WatchTxOptions): Promise<WatchTxResult> {\n const clock = options.clock;\n const engine = createConfirmationEngine({\n rpc: options.rpc,\n ...(options.rpcSubscriptions ? { rpcSubscriptions: options.rpcSubscriptions } : {}),\n ...(clock ? { clock } : {}),\n });\n\n const updates: WatchTxUpdate[] = [];\n const now = (): number => clock?.now() ?? 0;\n const push = (state: WatchTxUpdate['state'], detail: string): void => {\n const update: WatchTxUpdate = { at: now(), state, detail };\n updates.push(update);\n options.onUpdate?.(update);\n };\n\n push('watching', `commitment=${options.commitment ?? 'confirmed'}`);\n\n const outcome = await engine.confirm(signature, {\n commitment: options.commitment ?? 'confirmed',\n lastValidBlockHeight: options.lastValidBlockHeight,\n ...(options.pollIntervalMs !== undefined ? { pollIntervalMs: options.pollIntervalMs } : {}),\n ...(options.blockHeightIntervalMs !== undefined ? { blockHeightIntervalMs: options.blockHeightIntervalMs } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n\n switch (outcome.type) {\n case 'confirmed':\n push('confirmed', `slot ${outcome.slot} (${outcome.confirmationStatus})`);\n return { signature, outcome: 'confirmed', slot: outcome.slot, updates };\n case 'failed':\n push('failed', 'on-chain execution error');\n return { signature, outcome: 'failed', slot: outcome.slot, updates };\n case 'expired':\n push('expired', `block height ${outcome.blockHeight} > ${outcome.lastValidBlockHeight}`);\n return { signature, outcome: 'expired', slot: null, updates };\n default:\n push('aborted', 'watch aborted');\n return { signature, outcome: 'aborted', slot: null, updates };\n }\n}\n"," \n// Command orchestrators — live I/O + rendering, excluded from coverage. The pure\n// data layer (src/data/**) is what's tested; this wires it to real RPCs + stdout.\nimport { readFileSync } from 'node:fs';\nimport { createSolanaRpc, createSolanaRpcSubscriptions } from '@solana/kit';\nimport { asSenderRpc } from '@rpc-bastion/sender';\nimport { createResilientRpc, systemClock } from '@rpc-bastion/core';\nimport { doctorReportToJson, runDoctor, type DoctorRpc } from '../data/doctor';\nimport { parseConfig, resolveEndpoints } from '../data/config';\nimport { pushSample, summarizeSnapshot } from '../data/monitor';\nimport {\n SCENARIOS,\n listScenarios,\n runSimulation,\n summarizeSimulation,\n type SimulationTick,\n} from '../data/simulate';\nimport { watchTransaction } from '../data/watch-tx';\nimport { flagBool, flagInt, flagString, type ParsedArgs } from '../data/args';\nimport { clearScreen, sleep } from './ansi';\nimport {\n renderDoctor,\n renderMonitor,\n renderSimulationHeader,\n renderSimulationLiveTick,\n renderSimulationSummary,\n renderSimulationTick,\n renderWatchTx,\n} from './render';\nimport { color, print } from './ansi';\n\n/** Reads endpoints from --endpoints or --config. */\nfunction endpointsFromArgs(args: ParsedArgs): string[] {\n const configPath = flagString(args, 'config');\n const config = configPath ? parseConfig(readFileSync(configPath, 'utf8')) : undefined;\n const endpoints = flagString(args, 'endpoints');\n return resolveEndpoints({ ...(endpoints ? { endpoints } : {}), ...(config ? { config } : {}) });\n}\n\n/** A real per-endpoint Kit RPC, adapted to the DoctorRpc surface. */\nfunction doctorRpcFor(url: string): DoctorRpc {\n return createSolanaRpc(url) as unknown as DoctorRpc;\n}\n\nexport async function runDoctorCommand(args: ParsedArgs): Promise<void> {\n const urls = endpointsFromArgs(args);\n const report = await runDoctor(urls, {\n rpcFactory: doctorRpcFor,\n probes: flagInt(args, 'probes', 5),\n clock: systemClock,\n });\n if (flagBool(args, 'json')) {\n print(doctorReportToJson(report));\n } else {\n renderDoctor(report);\n }\n}\n\nexport async function runWatchTxCommand(args: ParsedArgs): Promise<void> {\n const sig = args.positionals[0];\n if (!sig) throw new Error('usage: bastion watch-tx <signature> --endpoints <urls>');\n const urls = endpointsFromArgs(args);\n const rpc = asSenderRpc(createSolanaRpc(urls[0]!));\n const subs = createSolanaRpcSubscriptions(urls[0]!.replace(/^http/, 'ws'));\n const lvbh = BigInt(flagString(args, 'last-valid-block-height') ?? '0');\n const result = await watchTransaction(sig, {\n rpc,\n rpcSubscriptions: subs as never,\n lastValidBlockHeight: lvbh,\n clock: systemClock,\n onUpdate: (u) => print(`${color.dim(String(u.at))} ${u.state} ${u.detail}`),\n });\n renderWatchTx(result);\n}\n\nexport async function runSimulateCommand(args: ParsedArgs): Promise<void> {\n const name = flagString(args, 'scenario');\n if (!name || flagBool(args, 'list')) {\n print(color.bold('Available scenarios:'));\n for (const s of listScenarios()) print(` ${color.cyan(s.name)} — ${s.description}`);\n return;\n }\n const scenario = SCENARIOS[name];\n if (!scenario) throw new Error(`unknown scenario \"${name}\" (try --list)`);\n\n if (flagBool(args, 'live')) {\n await runSimulateLive(args);\n return;\n }\n\n // Non-live: drive the mock chain + clock with a tick counter (no real sleeps).\n let t = 0;\n await runSimulation(scenario, {\n now: () => t,\n advance: (ms) => {\n t += ms;\n },\n onTick: (tick) => renderSimulationTick(tick),\n });\n print();\n print(color.dim(`scenario \"${scenario.name}\" complete`));\n}\n\n/**\n * The cinematic `--live` view: a paced, scrolling feed of the arc — healthy\n * probes → injected outage (breaker opens, traffic reroutes) → recovery\n * (half-open trial → closed) → a closing health table and the \"0 failed user\n * calls\" thesis. The simulation itself is the deterministic in-process mock, so\n * the data never depends on real latency; only the inter-beat pacing is real\n * (capped, so it stays loop-friendly regardless of host speed).\n */\nasync function runSimulateLive(args: ParsedArgs): Promise<void> {\n const scenario = SCENARIOS[flagString(args, 'scenario')!]!;\n // Pacing per beat, capped to 200–700ms so a viewer can follow without dragging.\n const beatMs = Math.max(200, Math.min(700, flagInt(args, 'beat', 420)));\n\n clearScreen();\n renderSimulationHeader(scenario);\n\n const collected: SimulationTick[] = [];\n // A hybrid clock: the plan timeline is anchored to tick boundaries (`base`), but\n // within a tick `now()` also tracks *real* elapsed time. The chaos transport\n // really sleeps its injected latency, so this lets the SDK's latency EWMA read a\n // realistic number — the bars animate — without perturbing the fault timeline.\n let base = 0;\n let anchor = performance.now();\n await runSimulation(scenario, {\n now: () => base + (performance.now() - anchor),\n advance: (ms) => {\n base += ms;\n anchor = performance.now();\n },\n onTick: (tick) => {\n collected.push(tick);\n },\n });\n\n for (const tick of collected) {\n renderSimulationLiveTick(tick);\n print();\n await sleep(beatMs);\n }\n\n const last = collected[collected.length - 1];\n if (last) renderSimulationSummary(last, summarizeSimulation(collected));\n}\n\nexport async function runMonitorCommand(args: ParsedArgs): Promise<void> {\n const urls = endpointsFromArgs(args);\n const { pool, rpc } = createResilientRpc(urls.map((url) => ({ url })));\n const history: Record<string, number[]> = {};\n const intervalMs = flagInt(args, 'interval', 1000);\n\n const tick = async (): Promise<void> => {\n try {\n await rpc.getSlot().send();\n } catch {\n /* health model absorbs failures */\n }\n const snapshot = pool.getHealthSnapshot();\n for (const h of snapshot) history[h.url] = pushSample(history[h.url] ?? [], h.latencyEwmaMs);\n clearScreen();\n print(color.bold('bastion monitor') + color.dim(' (ctrl-c to exit)'));\n print();\n renderMonitor(summarizeSnapshot(snapshot), history);\n };\n\n await tick();\n const timer = setInterval(() => void tick(), intervalMs);\n // Run until the process is interrupted.\n await new Promise<void>((resolve) => {\n process.on('SIGINT', () => {\n clearInterval(timer);\n resolve();\n });\n });\n}\n\nexport function runHelp(): void {\n print(color.bold('bastion') + ' — Solana RPC/transaction resilience diagnostics');\n print();\n print('Commands:');\n print(` ${color.cyan('doctor')} --endpoints <urls> | --config <file> [--probes N] [--json]`);\n print(` ${color.cyan('monitor')} --endpoints <urls> | --config <file> [--interval ms]`);\n print(` ${color.cyan('watch-tx')} <signature> --endpoints <urls>`);\n print(` ${color.cyan('simulate')} --scenario <name> [--live] | --list`);\n}\n\n/**\n * The CLI entry: parse argv → route → run the handler. Returns the exit code.\n * Lives in the I/O layer (excluded from coverage); the pure `route` it calls is\n * tested in `cli.test.ts`.\n */\nexport async function main(argv: readonly string[]): Promise<number> {\n const { parseArgs } = await import('../data/args');\n const { route } = await import('../cli');\n const args = parseArgs(argv);\n try {\n switch (route(args)) {\n case 'doctor':\n await runDoctorCommand(args);\n break;\n case 'monitor':\n await runMonitorCommand(args);\n break;\n case 'watch-tx':\n await runWatchTxCommand(args);\n break;\n case 'simulate':\n await runSimulateCommand(args);\n break;\n default:\n runHelp();\n }\n return 0;\n } catch (e) {\n console.error(`bastion: ${e instanceof Error ? e.message : String(e)}`);\n return 1;\n }\n}\n","// Rendering layer — excluded from coverage (see vitest.config.ts). Pure ANSI, no deps.\n\n/** ANSI color helpers (no-op if NO_COLOR is set). */\nconst useColor = !process.env.NO_COLOR;\nconst wrap = (code: string) => (s: string): string => (useColor ? `\u001b[${code}m${s}\u001b[0m` : s);\n\nexport const color = {\n green: wrap('32'),\n yellow: wrap('33'),\n red: wrap('31'),\n dim: wrap('2'),\n bold: wrap('1'),\n cyan: wrap('36'),\n};\n\n/** A green/yellow/red status dot. */\nexport function dot(kind: 'green' | 'yellow' | 'red'): string {\n const ch = '●';\n return kind === 'green' ? color.green(ch) : kind === 'yellow' ? color.yellow(ch) : color.red(ch);\n}\n\n/** Renders a simple fixed-width table. */\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => stripAnsi(r[i] ?? '').length)));\n const pad = (s: string, w: number): string => s + ' '.repeat(Math.max(0, w - stripAnsi(s).length));\n const line = (cols: string[]): string => cols.map((c, i) => pad(c, widths[i]!)).join(' ');\n const head = color.bold(line(headers));\n const sep = color.dim(widths.map((w) => '─'.repeat(w)).join(' '));\n return [head, sep, ...rows.map(line)].join('\\n');\n}\n\nconst SPARK = '▁▂▃▄▅▆▇█';\n\n/** Renders a unicode sparkline from a numeric series. */\nexport function sparkline(values: readonly number[]): string {\n if (values.length === 0) return '';\n const max = Math.max(...values, 1);\n return values.map((v) => SPARK[Math.min(SPARK.length - 1, Math.floor((v / max) * (SPARK.length - 1)))]).join('');\n}\n\n/** Strips ANSI escapes for width calculations. */\nexport function stripAnsi(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\u001b\\[[0-9;]*m/g, '');\n}\n\n/** Clears the screen + moves the cursor home (for live views). */\nexport function clearScreen(): void {\n process.stdout.write('\u001b[2J\u001b[H');\n}\n\nexport function print(line = ''): void {\n console.log(line);\n}\n\n/** A compact horizontal bar (0..1 → filled blocks) for latency/traffic. */\nexport function bar(fraction: number, width = 10): string {\n const f = Math.max(0, Math.min(1, fraction));\n const filled = Math.round(f * width);\n return '█'.repeat(filled) + color.dim('░'.repeat(width - filled));\n}\n\n/** Breaker state as a coloured word: CLOSED green · HALF-OPEN yellow · OPEN red. */\nexport function breakerWord(state: 'closed' | 'half-open' | 'open'): string {\n const label = state.toUpperCase();\n return state === 'open' ? color.red(label) : state === 'half-open' ? color.yellow(label) : color.green(label);\n}\n\nconst SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/** One spinner frame for index `i` (cycles). */\nexport function spinnerFrame(i: number): string {\n return color.cyan(SPINNER[i % SPINNER.length]!);\n}\n\n/** A dim, hacker-movie style inline comment, e.g. `# rerouting traffic`. */\nexport function comment(text: string): string {\n return color.dim(`# ${text}`);\n}\n\n/** Sleeps `ms` real-time (for live-view pacing; capped by the caller). */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Writes without a trailing newline (for in-place spinner/probe lines). */\nexport function write(s: string): void {\n process.stdout.write(s);\n}\n","// Rendering layer — excluded from coverage. Turns pure data-layer results into ANSI.\nimport type { DoctorReport } from '../data/doctor';\nimport type { MonitorSummary } from '../data/monitor';\nimport type { Scenario, SimulationSummary, SimulationTick, TickEvent } from '../data/simulate';\nimport type { WatchTxResult } from '../data/watch-tx';\nimport { bar, breakerWord, color, comment, dot, print, sparkline, table } from './ansi';\n\nexport function renderDoctor(report: DoctorReport): void {\n const rows = report.endpoints.map((e) => [\n e.reachable ? dot('green') : dot('red'),\n e.url,\n e.latencyP50Ms === null ? '—' : `${e.latencyP50Ms}ms`,\n e.health ?? '—',\n e.slot === null ? '—' : String(e.slot),\n e.slotLag === null ? '—' : `+${e.slotLag}`,\n e.version ?? '—',\n e.error ? color.red(e.error) : '',\n ]);\n print(table(['', 'endpoint', 'p50', 'health', 'slot', 'lag', 'version', 'error'], rows));\n print();\n print(color.dim(`${report.reachable}/${report.total} reachable · cluster slot ${report.clusterMaxSlot ?? '—'}`));\n}\n\nexport function renderMonitor(summary: MonitorSummary, history: Record<string, number[]>): void {\n const rows = summary.rows.map((r) => [\n dot(r.dot),\n r.url,\n `${r.latencyMs}ms`,\n sparkline(history[r.url] ?? []),\n `${r.errorRatePct}%`,\n r.slotLag === null ? '—' : `+${r.slotLag}`,\n r.breaker,\n String(r.inFlight),\n ]);\n print(table(['', 'endpoint', 'latency', 'trend', 'err', 'lag', 'breaker', 'inflight'], rows));\n print();\n print(color.dim(`${summary.healthy}/${summary.total} healthy · max lag ${summary.maxSlotLag ?? 0}`));\n}\n\nexport function renderWatchTx(result: WatchTxResult): void {\n for (const u of result.updates) {\n const c = u.state === 'confirmed' ? color.green : u.state === 'watching' ? color.cyan : color.red;\n print(`${color.dim(String(u.at))} ${c(u.state)} ${u.detail}`);\n }\n}\n\nexport function renderSimulationTick(tick: SimulationTick): void {\n const dots = tick.snapshot\n .map((h) => {\n const k = h.breaker === 'open' ? 'red' : h.errorRate > 0.1 ? 'yellow' : 'green';\n return `${dot(k)} ${h.url}`;\n })\n .join(' ');\n print(`tick ${String(tick.tick).padStart(2)} ${dots}`);\n}\n\n// ── Cinematic `--live` rendering ───────────────────────────────────────────────\n// One screen, redrawn each beat: a header, the live endpoint board, and a scroll\n// of narrative events. The pacing (sleeps) lives in the command orchestrator.\n\n/** Maps a health row to its status dot colour. */\nfunction dotKind(h: SimulationTick['snapshot'][number]): 'green' | 'yellow' | 'red' {\n if (h.breaker === 'open' || h.status === 'broken') return 'red';\n if (h.breaker === 'half-open' || h.status === 'degraded' || h.errorRate > 0.1) return 'yellow';\n return 'green';\n}\n\n/** The opening title card for a live run. */\nexport function renderSimulationHeader(scenario: Scenario): void {\n print(color.bold('bastion simulate') + color.dim(` · scenario: ${scenario.name}`));\n print(color.dim(scenario.description));\n print();\n}\n\n/**\n * The live endpoint board for one tick: a status dot, the breaker word, a latency\n * bar, and which endpoint served this tick's traffic — followed by a compact\n * probe line, and any *narrative* events (failover, breaker flips) called out on\n * their own coloured lines so the arc beats stand out in the scroll.\n */\nexport function renderSimulationLiveTick(tick: SimulationTick): void {\n const maxLat = Math.max(60, ...tick.snapshot.map((h) => h.latencyEwmaMs));\n for (const h of tick.snapshot) {\n const served = tick.servedBy === h.url ? color.cyan(' ◀ traffic') : '';\n const lat = h.latencyEwmaMs > 0 ? `${bar(h.latencyEwmaMs / maxLat, 8)} ${Math.round(h.latencyEwmaMs)}ms` : bar(0, 8);\n print(` ${dot(dotKind(h))} ${h.url.padEnd(6)} ${breakerWord(h.breaker).padEnd(18)} ${lat}${served}`);\n }\n // Compact probe summary for the tick (endpoint·latency, or ✕ for a failed call).\n const probes = (tick.events ?? [])\n .filter((e) => e.kind === 'served' || e.kind === 'error')\n .map((e) => (e.kind === 'served' ? `${e.endpoint} ${e.detail}` : color.red(`${e.endpoint} ✕`)));\n if (probes.length) print(color.dim(` probes: `) + probes.join(color.dim(' · ')));\n // The arc beats — breaker flips and failovers — each on their own loud line.\n for (const ev of tick.events ?? []) {\n if (ev.kind === 'served' || ev.kind === 'error') continue;\n print(` ${renderTickEvent(ev)}`);\n }\n}\n\n/** One narrative event line: coloured to its arc beat. */\nfunction renderTickEvent(ev: TickEvent): string {\n switch (ev.kind) {\n case 'failover':\n return color.yellow('↻ failover ') + color.dim(ev.detail);\n case 'breaker-open':\n return color.red(`✕ breaker ${ev.endpoint} OPEN `) + comment('ejecting endpoint, rerouting traffic');\n case 'breaker-half-open':\n return color.yellow(`◐ breaker ${ev.endpoint} HALF-OPEN `) + comment('trial request');\n case 'breaker-closed':\n return color.green(`✓ breaker ${ev.endpoint} CLOSED `) + comment('recovered, back in rotation');\n default:\n return color.dim(`· ${ev.endpoint} ${ev.detail}`);\n }\n}\n\n/** The closing card: final health table + the \"0 failed user calls\" thesis. */\nexport function renderSimulationSummary(finalTick: SimulationTick, summary: SimulationSummary): void {\n print();\n print(color.bold('final health'));\n const rows = finalTick.snapshot.map((h) => {\n const served = summary.perEndpoint.find((r) => r.url === h.url)?.served ?? 0;\n return [dot(dotKind(h)), h.url, breakerWord(h.breaker), `${Math.round(h.latencyEwmaMs)}ms`, `${served} served`];\n });\n print(table(['', 'endpoint', 'breaker', 'latency', 'traffic'], rows));\n print();\n\n const total = summary.userCallsTotal;\n const failed = summary.userCallsFailed;\n const thesis =\n failed === 0\n ? color.green(color.bold(`✓ 0 failed user calls`)) +\n color.dim(` across ${total} calls — ${summary.breakerOpens} breaker trip(s), every call served by a healthy endpoint`)\n : color.red(color.bold(`✕ ${failed}/${total} user calls failed`));\n print(thesis);\n}\n","#!/usr/bin/env node\n// The `bastion` executable. All logic lives in the data layer + ui/run; this is\n// just the entrypoint. Excluded from coverage (under no test harness).\nimport { main } from './run';\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (err) => {\n console.error(err);\n process.exitCode = 1;\n },\n);\n"]}
package/dist/bin.js ADDED
@@ -0,0 +1,323 @@
1
+ #!/usr/bin/env node
2
+ import { listScenarios, SCENARIOS, runSimulation, watchTransaction, runDoctor, doctorReportToJson, summarizeSimulation, parseConfig, resolveEndpoints, pushSample, summarizeSnapshot } from './chunk-F5AAJEDR.js';
3
+ import { flagString, flagBool, flagInt } from './chunk-Q2OA5HXD.js';
4
+ import { readFileSync } from 'fs';
5
+ import { createSolanaRpc, createSolanaRpcSubscriptions } from '@solana/kit';
6
+ import { asSenderRpc } from '@rpc-bastion/sender';
7
+ import { systemClock, createResilientRpc } from '@rpc-bastion/core';
8
+
9
+ // src/ui/ansi.ts
10
+ var useColor = !process.env.NO_COLOR;
11
+ var wrap = (code) => (s) => useColor ? `\x1B[${code}m${s}\x1B[0m` : s;
12
+ var color = {
13
+ green: wrap("32"),
14
+ yellow: wrap("33"),
15
+ red: wrap("31"),
16
+ dim: wrap("2"),
17
+ bold: wrap("1"),
18
+ cyan: wrap("36")
19
+ };
20
+ function dot(kind) {
21
+ const ch = "\u25CF";
22
+ return kind === "green" ? color.green(ch) : kind === "yellow" ? color.yellow(ch) : color.red(ch);
23
+ }
24
+ function table(headers, rows) {
25
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => stripAnsi(r[i] ?? "").length)));
26
+ const pad = (s, w) => s + " ".repeat(Math.max(0, w - stripAnsi(s).length));
27
+ const line = (cols) => cols.map((c, i) => pad(c, widths[i])).join(" ");
28
+ const head = color.bold(line(headers));
29
+ const sep = color.dim(widths.map((w) => "\u2500".repeat(w)).join(" "));
30
+ return [head, sep, ...rows.map(line)].join("\n");
31
+ }
32
+ var SPARK = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
33
+ function sparkline(values) {
34
+ if (values.length === 0) return "";
35
+ const max = Math.max(...values, 1);
36
+ return values.map((v) => SPARK[Math.min(SPARK.length - 1, Math.floor(v / max * (SPARK.length - 1)))]).join("");
37
+ }
38
+ function stripAnsi(s) {
39
+ return s.replace(/\[[0-9;]*m/g, "");
40
+ }
41
+ function clearScreen() {
42
+ process.stdout.write("\x1B[2J\x1B[H");
43
+ }
44
+ function print(line = "") {
45
+ console.log(line);
46
+ }
47
+ function bar(fraction, width = 10) {
48
+ const f = Math.max(0, Math.min(1, fraction));
49
+ const filled = Math.round(f * width);
50
+ return "\u2588".repeat(filled) + color.dim("\u2591".repeat(width - filled));
51
+ }
52
+ function breakerWord(state) {
53
+ const label = state.toUpperCase();
54
+ return state === "open" ? color.red(label) : state === "half-open" ? color.yellow(label) : color.green(label);
55
+ }
56
+ function comment(text) {
57
+ return color.dim(`# ${text}`);
58
+ }
59
+ function sleep(ms) {
60
+ return new Promise((resolve) => setTimeout(resolve, ms));
61
+ }
62
+
63
+ // src/ui/render.ts
64
+ function renderDoctor(report) {
65
+ const rows = report.endpoints.map((e) => [
66
+ e.reachable ? dot("green") : dot("red"),
67
+ e.url,
68
+ e.latencyP50Ms === null ? "\u2014" : `${e.latencyP50Ms}ms`,
69
+ e.health ?? "\u2014",
70
+ e.slot === null ? "\u2014" : String(e.slot),
71
+ e.slotLag === null ? "\u2014" : `+${e.slotLag}`,
72
+ e.version ?? "\u2014",
73
+ e.error ? color.red(e.error) : ""
74
+ ]);
75
+ print(table(["", "endpoint", "p50", "health", "slot", "lag", "version", "error"], rows));
76
+ print();
77
+ print(color.dim(`${report.reachable}/${report.total} reachable \xB7 cluster slot ${report.clusterMaxSlot ?? "\u2014"}`));
78
+ }
79
+ function renderMonitor(summary, history) {
80
+ const rows = summary.rows.map((r) => [
81
+ dot(r.dot),
82
+ r.url,
83
+ `${r.latencyMs}ms`,
84
+ sparkline(history[r.url] ?? []),
85
+ `${r.errorRatePct}%`,
86
+ r.slotLag === null ? "\u2014" : `+${r.slotLag}`,
87
+ r.breaker,
88
+ String(r.inFlight)
89
+ ]);
90
+ print(table(["", "endpoint", "latency", "trend", "err", "lag", "breaker", "inflight"], rows));
91
+ print();
92
+ print(color.dim(`${summary.healthy}/${summary.total} healthy \xB7 max lag ${summary.maxSlotLag ?? 0}`));
93
+ }
94
+ function renderWatchTx(result) {
95
+ for (const u of result.updates) {
96
+ const c = u.state === "confirmed" ? color.green : u.state === "watching" ? color.cyan : color.red;
97
+ print(`${color.dim(String(u.at))} ${c(u.state)} ${u.detail}`);
98
+ }
99
+ }
100
+ function renderSimulationTick(tick) {
101
+ const dots = tick.snapshot.map((h) => {
102
+ const k = h.breaker === "open" ? "red" : h.errorRate > 0.1 ? "yellow" : "green";
103
+ return `${dot(k)} ${h.url}`;
104
+ }).join(" ");
105
+ print(`tick ${String(tick.tick).padStart(2)} ${dots}`);
106
+ }
107
+ function dotKind(h) {
108
+ if (h.breaker === "open" || h.status === "broken") return "red";
109
+ if (h.breaker === "half-open" || h.status === "degraded" || h.errorRate > 0.1) return "yellow";
110
+ return "green";
111
+ }
112
+ function renderSimulationHeader(scenario) {
113
+ print(color.bold("bastion simulate") + color.dim(` \xB7 scenario: ${scenario.name}`));
114
+ print(color.dim(scenario.description));
115
+ print();
116
+ }
117
+ function renderSimulationLiveTick(tick) {
118
+ const maxLat = Math.max(60, ...tick.snapshot.map((h) => h.latencyEwmaMs));
119
+ for (const h of tick.snapshot) {
120
+ const served = tick.servedBy === h.url ? color.cyan(" \u25C0 traffic") : "";
121
+ const lat = h.latencyEwmaMs > 0 ? `${bar(h.latencyEwmaMs / maxLat, 8)} ${Math.round(h.latencyEwmaMs)}ms` : bar(0, 8);
122
+ print(` ${dot(dotKind(h))} ${h.url.padEnd(6)} ${breakerWord(h.breaker).padEnd(18)} ${lat}${served}`);
123
+ }
124
+ const probes = (tick.events ?? []).filter((e) => e.kind === "served" || e.kind === "error").map((e) => e.kind === "served" ? `${e.endpoint} ${e.detail}` : color.red(`${e.endpoint} \u2715`));
125
+ if (probes.length) print(color.dim(` probes: `) + probes.join(color.dim(" \xB7 ")));
126
+ for (const ev of tick.events ?? []) {
127
+ if (ev.kind === "served" || ev.kind === "error") continue;
128
+ print(` ${renderTickEvent(ev)}`);
129
+ }
130
+ }
131
+ function renderTickEvent(ev) {
132
+ switch (ev.kind) {
133
+ case "failover":
134
+ return color.yellow("\u21BB failover ") + color.dim(ev.detail);
135
+ case "breaker-open":
136
+ return color.red(`\u2715 breaker ${ev.endpoint} OPEN `) + comment("ejecting endpoint, rerouting traffic");
137
+ case "breaker-half-open":
138
+ return color.yellow(`\u25D0 breaker ${ev.endpoint} HALF-OPEN `) + comment("trial request");
139
+ case "breaker-closed":
140
+ return color.green(`\u2713 breaker ${ev.endpoint} CLOSED `) + comment("recovered, back in rotation");
141
+ default:
142
+ return color.dim(`\xB7 ${ev.endpoint} ${ev.detail}`);
143
+ }
144
+ }
145
+ function renderSimulationSummary(finalTick, summary) {
146
+ print();
147
+ print(color.bold("final health"));
148
+ const rows = finalTick.snapshot.map((h) => {
149
+ const served = summary.perEndpoint.find((r) => r.url === h.url)?.served ?? 0;
150
+ return [dot(dotKind(h)), h.url, breakerWord(h.breaker), `${Math.round(h.latencyEwmaMs)}ms`, `${served} served`];
151
+ });
152
+ print(table(["", "endpoint", "breaker", "latency", "traffic"], rows));
153
+ print();
154
+ const total = summary.userCallsTotal;
155
+ const failed = summary.userCallsFailed;
156
+ const thesis = failed === 0 ? color.green(color.bold(`\u2713 0 failed user calls`)) + color.dim(` across ${total} calls \u2014 ${summary.breakerOpens} breaker trip(s), every call served by a healthy endpoint`) : color.red(color.bold(`\u2715 ${failed}/${total} user calls failed`));
157
+ print(thesis);
158
+ }
159
+
160
+ // src/ui/run.ts
161
+ function endpointsFromArgs(args) {
162
+ const configPath = flagString(args, "config");
163
+ const config = configPath ? parseConfig(readFileSync(configPath, "utf8")) : void 0;
164
+ const endpoints = flagString(args, "endpoints");
165
+ return resolveEndpoints({ ...endpoints ? { endpoints } : {}, ...config ? { config } : {} });
166
+ }
167
+ function doctorRpcFor(url) {
168
+ return createSolanaRpc(url);
169
+ }
170
+ async function runDoctorCommand(args) {
171
+ const urls = endpointsFromArgs(args);
172
+ const report = await runDoctor(urls, {
173
+ rpcFactory: doctorRpcFor,
174
+ probes: flagInt(args, "probes", 5),
175
+ clock: systemClock
176
+ });
177
+ if (flagBool(args, "json")) {
178
+ print(doctorReportToJson(report));
179
+ } else {
180
+ renderDoctor(report);
181
+ }
182
+ }
183
+ async function runWatchTxCommand(args) {
184
+ const sig = args.positionals[0];
185
+ if (!sig) throw new Error("usage: bastion watch-tx <signature> --endpoints <urls>");
186
+ const urls = endpointsFromArgs(args);
187
+ const rpc = asSenderRpc(createSolanaRpc(urls[0]));
188
+ const subs = createSolanaRpcSubscriptions(urls[0].replace(/^http/, "ws"));
189
+ const lvbh = BigInt(flagString(args, "last-valid-block-height") ?? "0");
190
+ const result = await watchTransaction(sig, {
191
+ rpc,
192
+ rpcSubscriptions: subs,
193
+ lastValidBlockHeight: lvbh,
194
+ clock: systemClock,
195
+ onUpdate: (u) => print(`${color.dim(String(u.at))} ${u.state} ${u.detail}`)
196
+ });
197
+ renderWatchTx(result);
198
+ }
199
+ async function runSimulateCommand(args) {
200
+ const name = flagString(args, "scenario");
201
+ if (!name || flagBool(args, "list")) {
202
+ print(color.bold("Available scenarios:"));
203
+ for (const s of listScenarios()) print(` ${color.cyan(s.name)} \u2014 ${s.description}`);
204
+ return;
205
+ }
206
+ const scenario = SCENARIOS[name];
207
+ if (!scenario) throw new Error(`unknown scenario "${name}" (try --list)`);
208
+ if (flagBool(args, "live")) {
209
+ await runSimulateLive(args);
210
+ return;
211
+ }
212
+ let t = 0;
213
+ await runSimulation(scenario, {
214
+ now: () => t,
215
+ advance: (ms) => {
216
+ t += ms;
217
+ },
218
+ onTick: (tick) => renderSimulationTick(tick)
219
+ });
220
+ print();
221
+ print(color.dim(`scenario "${scenario.name}" complete`));
222
+ }
223
+ async function runSimulateLive(args) {
224
+ const scenario = SCENARIOS[flagString(args, "scenario")];
225
+ const beatMs = Math.max(200, Math.min(700, flagInt(args, "beat", 420)));
226
+ clearScreen();
227
+ renderSimulationHeader(scenario);
228
+ const collected = [];
229
+ let base = 0;
230
+ let anchor = performance.now();
231
+ await runSimulation(scenario, {
232
+ now: () => base + (performance.now() - anchor),
233
+ advance: (ms) => {
234
+ base += ms;
235
+ anchor = performance.now();
236
+ },
237
+ onTick: (tick) => {
238
+ collected.push(tick);
239
+ }
240
+ });
241
+ for (const tick of collected) {
242
+ renderSimulationLiveTick(tick);
243
+ print();
244
+ await sleep(beatMs);
245
+ }
246
+ const last = collected[collected.length - 1];
247
+ if (last) renderSimulationSummary(last, summarizeSimulation(collected));
248
+ }
249
+ async function runMonitorCommand(args) {
250
+ const urls = endpointsFromArgs(args);
251
+ const { pool, rpc } = createResilientRpc(urls.map((url) => ({ url })));
252
+ const history = {};
253
+ const intervalMs = flagInt(args, "interval", 1e3);
254
+ const tick = async () => {
255
+ try {
256
+ await rpc.getSlot().send();
257
+ } catch {
258
+ }
259
+ const snapshot = pool.getHealthSnapshot();
260
+ for (const h of snapshot) history[h.url] = pushSample(history[h.url] ?? [], h.latencyEwmaMs);
261
+ clearScreen();
262
+ print(color.bold("bastion monitor") + color.dim(" (ctrl-c to exit)"));
263
+ print();
264
+ renderMonitor(summarizeSnapshot(snapshot), history);
265
+ };
266
+ await tick();
267
+ const timer = setInterval(() => void tick(), intervalMs);
268
+ await new Promise((resolve) => {
269
+ process.on("SIGINT", () => {
270
+ clearInterval(timer);
271
+ resolve();
272
+ });
273
+ });
274
+ }
275
+ function runHelp() {
276
+ print(color.bold("bastion") + " \u2014 Solana RPC/transaction resilience diagnostics");
277
+ print();
278
+ print("Commands:");
279
+ print(` ${color.cyan("doctor")} --endpoints <urls> | --config <file> [--probes N] [--json]`);
280
+ print(` ${color.cyan("monitor")} --endpoints <urls> | --config <file> [--interval ms]`);
281
+ print(` ${color.cyan("watch-tx")} <signature> --endpoints <urls>`);
282
+ print(` ${color.cyan("simulate")} --scenario <name> [--live] | --list`);
283
+ }
284
+ async function main(argv) {
285
+ const { parseArgs } = await import('./args-O3XNV7QR.js');
286
+ const { route } = await import('./cli-64RAFQGB.js');
287
+ const args = parseArgs(argv);
288
+ try {
289
+ switch (route(args)) {
290
+ case "doctor":
291
+ await runDoctorCommand(args);
292
+ break;
293
+ case "monitor":
294
+ await runMonitorCommand(args);
295
+ break;
296
+ case "watch-tx":
297
+ await runWatchTxCommand(args);
298
+ break;
299
+ case "simulate":
300
+ await runSimulateCommand(args);
301
+ break;
302
+ default:
303
+ runHelp();
304
+ }
305
+ return 0;
306
+ } catch (e) {
307
+ console.error(`bastion: ${e instanceof Error ? e.message : String(e)}`);
308
+ return 1;
309
+ }
310
+ }
311
+
312
+ // src/ui/bin.ts
313
+ main(process.argv.slice(2)).then(
314
+ (code) => {
315
+ process.exitCode = code;
316
+ },
317
+ (err) => {
318
+ console.error(err);
319
+ process.exitCode = 1;
320
+ }
321
+ );
322
+ //# sourceMappingURL=bin.js.map
323
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ui/ansi.ts","../src/ui/render.ts","../src/ui/run.ts","../src/ui/bin.ts"],"names":[],"mappings":";;;;;;;;;AAGA,IAAM,QAAA,GAAW,CAAC,OAAA,CAAQ,GAAA,CAAI,QAAA;AAC9B,IAAM,IAAA,GAAO,CAAC,IAAA,KAAiB,CAAC,CAAA,KAAuB,WAAW,CAAA,KAAA,EAAK,IAAI,CAAA,CAAA,EAAI,CAAC,CAAA,OAAA,CAAA,GAAS,CAAA;AAElF,IAAM,KAAA,GAAQ;AAAA,EACnB,KAAA,EAAO,KAAK,IAAI,CAAA;AAAA,EAChB,MAAA,EAAQ,KAAK,IAAI,CAAA;AAAA,EACjB,GAAA,EAAK,KAAK,IAAI,CAAA;AAAA,EACd,GAAA,EAAK,KAAK,GAAG,CAAA;AAAA,EACb,IAAA,EAAM,KAAK,GAAG,CAAA;AAAA,EACd,IAAA,EAAM,KAAK,IAAI;AACjB,CAAA;AAGO,SAAS,IAAI,IAAA,EAA0C;AAC5D,EAAA,MAAM,EAAA,GAAK,QAAA;AACX,EAAA,OAAO,IAAA,KAAS,OAAA,GAAU,KAAA,CAAM,KAAA,CAAM,EAAE,CAAA,GAAI,IAAA,KAAS,QAAA,GAAW,KAAA,CAAM,MAAA,CAAO,EAAE,CAAA,GAAI,KAAA,CAAM,IAAI,EAAE,CAAA;AACjG;AAGO,SAAS,KAAA,CAAM,SAAmB,IAAA,EAA0B;AACjE,EAAA,MAAM,MAAA,GAAS,QAAQ,GAAA,CAAI,CAAC,GAAG,CAAA,KAAM,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,MAAA,EAAQ,GAAG,KAAK,GAAA,CAAI,CAAC,CAAA,KAAM,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,CAAA;AACjD,EAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,OAAO,mBAAQ,CAAA;AACvC,EAAA,MAAM,IAAA,GAAO,UAAU,IAAI,CAAA;AAC3B,EAAA,IAAI;AACF,IAAA,QAAQ,KAAA,CAAM,IAAI,CAAA;AAAG,MACnB,KAAK,QAAA;AACH,QAAA,MAAM,iBAAiB,IAAI,CAAA;AAC3B,QAAA;AAAA,MACF,KAAK,SAAA;AACH,QAAA,MAAM,kBAAkB,IAAI,CAAA;AAC5B,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,MAAM,kBAAkB,IAAI,CAAA;AAC5B,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,MAAM,mBAAmB,IAAI,CAAA;AAC7B,QAAA;AAAA,MACF;AACE,QAAA,OAAA,EAAQ;AAAA;AAEZ,IAAA,OAAO,CAAA;AAAA,EACT,SAAS,CAAA,EAAG;AACV,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAY,CAAA,YAAa,KAAA,GAAQ,EAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA,CAAE,CAAA;AACtE,IAAA,OAAO,CAAA;AAAA,EACT;AACF;;;ACtNA,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,EAC1B,CAAC,IAAA,KAAS;AACR,IAAA,OAAA,CAAQ,QAAA,GAAW,IAAA;AAAA,EACrB,CAAA;AAAA,EACA,CAAC,GAAA,KAAQ;AACP,IAAA,OAAA,CAAQ,MAAM,GAAG,CAAA;AACjB,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA","file":"bin.js","sourcesContent":["// Rendering layer — excluded from coverage (see vitest.config.ts). Pure ANSI, no deps.\n\n/** ANSI color helpers (no-op if NO_COLOR is set). */\nconst useColor = !process.env.NO_COLOR;\nconst wrap = (code: string) => (s: string): string => (useColor ? `\u001b[${code}m${s}\u001b[0m` : s);\n\nexport const color = {\n green: wrap('32'),\n yellow: wrap('33'),\n red: wrap('31'),\n dim: wrap('2'),\n bold: wrap('1'),\n cyan: wrap('36'),\n};\n\n/** A green/yellow/red status dot. */\nexport function dot(kind: 'green' | 'yellow' | 'red'): string {\n const ch = '●';\n return kind === 'green' ? color.green(ch) : kind === 'yellow' ? color.yellow(ch) : color.red(ch);\n}\n\n/** Renders a simple fixed-width table. */\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => stripAnsi(r[i] ?? '').length)));\n const pad = (s: string, w: number): string => s + ' '.repeat(Math.max(0, w - stripAnsi(s).length));\n const line = (cols: string[]): string => cols.map((c, i) => pad(c, widths[i]!)).join(' ');\n const head = color.bold(line(headers));\n const sep = color.dim(widths.map((w) => '─'.repeat(w)).join(' '));\n return [head, sep, ...rows.map(line)].join('\\n');\n}\n\nconst SPARK = '▁▂▃▄▅▆▇█';\n\n/** Renders a unicode sparkline from a numeric series. */\nexport function sparkline(values: readonly number[]): string {\n if (values.length === 0) return '';\n const max = Math.max(...values, 1);\n return values.map((v) => SPARK[Math.min(SPARK.length - 1, Math.floor((v / max) * (SPARK.length - 1)))]).join('');\n}\n\n/** Strips ANSI escapes for width calculations. */\nexport function stripAnsi(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\u001b\\[[0-9;]*m/g, '');\n}\n\n/** Clears the screen + moves the cursor home (for live views). */\nexport function clearScreen(): void {\n process.stdout.write('\u001b[2J\u001b[H');\n}\n\nexport function print(line = ''): void {\n console.log(line);\n}\n\n/** A compact horizontal bar (0..1 → filled blocks) for latency/traffic. */\nexport function bar(fraction: number, width = 10): string {\n const f = Math.max(0, Math.min(1, fraction));\n const filled = Math.round(f * width);\n return '█'.repeat(filled) + color.dim('░'.repeat(width - filled));\n}\n\n/** Breaker state as a coloured word: CLOSED green · HALF-OPEN yellow · OPEN red. */\nexport function breakerWord(state: 'closed' | 'half-open' | 'open'): string {\n const label = state.toUpperCase();\n return state === 'open' ? color.red(label) : state === 'half-open' ? color.yellow(label) : color.green(label);\n}\n\nconst SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/** One spinner frame for index `i` (cycles). */\nexport function spinnerFrame(i: number): string {\n return color.cyan(SPINNER[i % SPINNER.length]!);\n}\n\n/** A dim, hacker-movie style inline comment, e.g. `# rerouting traffic`. */\nexport function comment(text: string): string {\n return color.dim(`# ${text}`);\n}\n\n/** Sleeps `ms` real-time (for live-view pacing; capped by the caller). */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Writes without a trailing newline (for in-place spinner/probe lines). */\nexport function write(s: string): void {\n process.stdout.write(s);\n}\n","// Rendering layer — excluded from coverage. Turns pure data-layer results into ANSI.\nimport type { DoctorReport } from '../data/doctor';\nimport type { MonitorSummary } from '../data/monitor';\nimport type { Scenario, SimulationSummary, SimulationTick, TickEvent } from '../data/simulate';\nimport type { WatchTxResult } from '../data/watch-tx';\nimport { bar, breakerWord, color, comment, dot, print, sparkline, table } from './ansi';\n\nexport function renderDoctor(report: DoctorReport): void {\n const rows = report.endpoints.map((e) => [\n e.reachable ? dot('green') : dot('red'),\n e.url,\n e.latencyP50Ms === null ? '—' : `${e.latencyP50Ms}ms`,\n e.health ?? '—',\n e.slot === null ? '—' : String(e.slot),\n e.slotLag === null ? '—' : `+${e.slotLag}`,\n e.version ?? '—',\n e.error ? color.red(e.error) : '',\n ]);\n print(table(['', 'endpoint', 'p50', 'health', 'slot', 'lag', 'version', 'error'], rows));\n print();\n print(color.dim(`${report.reachable}/${report.total} reachable · cluster slot ${report.clusterMaxSlot ?? '—'}`));\n}\n\nexport function renderMonitor(summary: MonitorSummary, history: Record<string, number[]>): void {\n const rows = summary.rows.map((r) => [\n dot(r.dot),\n r.url,\n `${r.latencyMs}ms`,\n sparkline(history[r.url] ?? []),\n `${r.errorRatePct}%`,\n r.slotLag === null ? '—' : `+${r.slotLag}`,\n r.breaker,\n String(r.inFlight),\n ]);\n print(table(['', 'endpoint', 'latency', 'trend', 'err', 'lag', 'breaker', 'inflight'], rows));\n print();\n print(color.dim(`${summary.healthy}/${summary.total} healthy · max lag ${summary.maxSlotLag ?? 0}`));\n}\n\nexport function renderWatchTx(result: WatchTxResult): void {\n for (const u of result.updates) {\n const c = u.state === 'confirmed' ? color.green : u.state === 'watching' ? color.cyan : color.red;\n print(`${color.dim(String(u.at))} ${c(u.state)} ${u.detail}`);\n }\n}\n\nexport function renderSimulationTick(tick: SimulationTick): void {\n const dots = tick.snapshot\n .map((h) => {\n const k = h.breaker === 'open' ? 'red' : h.errorRate > 0.1 ? 'yellow' : 'green';\n return `${dot(k)} ${h.url}`;\n })\n .join(' ');\n print(`tick ${String(tick.tick).padStart(2)} ${dots}`);\n}\n\n// ── Cinematic `--live` rendering ───────────────────────────────────────────────\n// One screen, redrawn each beat: a header, the live endpoint board, and a scroll\n// of narrative events. The pacing (sleeps) lives in the command orchestrator.\n\n/** Maps a health row to its status dot colour. */\nfunction dotKind(h: SimulationTick['snapshot'][number]): 'green' | 'yellow' | 'red' {\n if (h.breaker === 'open' || h.status === 'broken') return 'red';\n if (h.breaker === 'half-open' || h.status === 'degraded' || h.errorRate > 0.1) return 'yellow';\n return 'green';\n}\n\n/** The opening title card for a live run. */\nexport function renderSimulationHeader(scenario: Scenario): void {\n print(color.bold('bastion simulate') + color.dim(` · scenario: ${scenario.name}`));\n print(color.dim(scenario.description));\n print();\n}\n\n/**\n * The live endpoint board for one tick: a status dot, the breaker word, a latency\n * bar, and which endpoint served this tick's traffic — followed by a compact\n * probe line, and any *narrative* events (failover, breaker flips) called out on\n * their own coloured lines so the arc beats stand out in the scroll.\n */\nexport function renderSimulationLiveTick(tick: SimulationTick): void {\n const maxLat = Math.max(60, ...tick.snapshot.map((h) => h.latencyEwmaMs));\n for (const h of tick.snapshot) {\n const served = tick.servedBy === h.url ? color.cyan(' ◀ traffic') : '';\n const lat = h.latencyEwmaMs > 0 ? `${bar(h.latencyEwmaMs / maxLat, 8)} ${Math.round(h.latencyEwmaMs)}ms` : bar(0, 8);\n print(` ${dot(dotKind(h))} ${h.url.padEnd(6)} ${breakerWord(h.breaker).padEnd(18)} ${lat}${served}`);\n }\n // Compact probe summary for the tick (endpoint·latency, or ✕ for a failed call).\n const probes = (tick.events ?? [])\n .filter((e) => e.kind === 'served' || e.kind === 'error')\n .map((e) => (e.kind === 'served' ? `${e.endpoint} ${e.detail}` : color.red(`${e.endpoint} ✕`)));\n if (probes.length) print(color.dim(` probes: `) + probes.join(color.dim(' · ')));\n // The arc beats — breaker flips and failovers — each on their own loud line.\n for (const ev of tick.events ?? []) {\n if (ev.kind === 'served' || ev.kind === 'error') continue;\n print(` ${renderTickEvent(ev)}`);\n }\n}\n\n/** One narrative event line: coloured to its arc beat. */\nfunction renderTickEvent(ev: TickEvent): string {\n switch (ev.kind) {\n case 'failover':\n return color.yellow('↻ failover ') + color.dim(ev.detail);\n case 'breaker-open':\n return color.red(`✕ breaker ${ev.endpoint} OPEN `) + comment('ejecting endpoint, rerouting traffic');\n case 'breaker-half-open':\n return color.yellow(`◐ breaker ${ev.endpoint} HALF-OPEN `) + comment('trial request');\n case 'breaker-closed':\n return color.green(`✓ breaker ${ev.endpoint} CLOSED `) + comment('recovered, back in rotation');\n default:\n return color.dim(`· ${ev.endpoint} ${ev.detail}`);\n }\n}\n\n/** The closing card: final health table + the \"0 failed user calls\" thesis. */\nexport function renderSimulationSummary(finalTick: SimulationTick, summary: SimulationSummary): void {\n print();\n print(color.bold('final health'));\n const rows = finalTick.snapshot.map((h) => {\n const served = summary.perEndpoint.find((r) => r.url === h.url)?.served ?? 0;\n return [dot(dotKind(h)), h.url, breakerWord(h.breaker), `${Math.round(h.latencyEwmaMs)}ms`, `${served} served`];\n });\n print(table(['', 'endpoint', 'breaker', 'latency', 'traffic'], rows));\n print();\n\n const total = summary.userCallsTotal;\n const failed = summary.userCallsFailed;\n const thesis =\n failed === 0\n ? color.green(color.bold(`✓ 0 failed user calls`)) +\n color.dim(` across ${total} calls — ${summary.breakerOpens} breaker trip(s), every call served by a healthy endpoint`)\n : color.red(color.bold(`✕ ${failed}/${total} user calls failed`));\n print(thesis);\n}\n"," \n// Command orchestrators — live I/O + rendering, excluded from coverage. The pure\n// data layer (src/data/**) is what's tested; this wires it to real RPCs + stdout.\nimport { readFileSync } from 'node:fs';\nimport { createSolanaRpc, createSolanaRpcSubscriptions } from '@solana/kit';\nimport { asSenderRpc } from '@rpc-bastion/sender';\nimport { createResilientRpc, systemClock } from '@rpc-bastion/core';\nimport { doctorReportToJson, runDoctor, type DoctorRpc } from '../data/doctor';\nimport { parseConfig, resolveEndpoints } from '../data/config';\nimport { pushSample, summarizeSnapshot } from '../data/monitor';\nimport {\n SCENARIOS,\n listScenarios,\n runSimulation,\n summarizeSimulation,\n type SimulationTick,\n} from '../data/simulate';\nimport { watchTransaction } from '../data/watch-tx';\nimport { flagBool, flagInt, flagString, type ParsedArgs } from '../data/args';\nimport { clearScreen, sleep } from './ansi';\nimport {\n renderDoctor,\n renderMonitor,\n renderSimulationHeader,\n renderSimulationLiveTick,\n renderSimulationSummary,\n renderSimulationTick,\n renderWatchTx,\n} from './render';\nimport { color, print } from './ansi';\n\n/** Reads endpoints from --endpoints or --config. */\nfunction endpointsFromArgs(args: ParsedArgs): string[] {\n const configPath = flagString(args, 'config');\n const config = configPath ? parseConfig(readFileSync(configPath, 'utf8')) : undefined;\n const endpoints = flagString(args, 'endpoints');\n return resolveEndpoints({ ...(endpoints ? { endpoints } : {}), ...(config ? { config } : {}) });\n}\n\n/** A real per-endpoint Kit RPC, adapted to the DoctorRpc surface. */\nfunction doctorRpcFor(url: string): DoctorRpc {\n return createSolanaRpc(url) as unknown as DoctorRpc;\n}\n\nexport async function runDoctorCommand(args: ParsedArgs): Promise<void> {\n const urls = endpointsFromArgs(args);\n const report = await runDoctor(urls, {\n rpcFactory: doctorRpcFor,\n probes: flagInt(args, 'probes', 5),\n clock: systemClock,\n });\n if (flagBool(args, 'json')) {\n print(doctorReportToJson(report));\n } else {\n renderDoctor(report);\n }\n}\n\nexport async function runWatchTxCommand(args: ParsedArgs): Promise<void> {\n const sig = args.positionals[0];\n if (!sig) throw new Error('usage: bastion watch-tx <signature> --endpoints <urls>');\n const urls = endpointsFromArgs(args);\n const rpc = asSenderRpc(createSolanaRpc(urls[0]!));\n const subs = createSolanaRpcSubscriptions(urls[0]!.replace(/^http/, 'ws'));\n const lvbh = BigInt(flagString(args, 'last-valid-block-height') ?? '0');\n const result = await watchTransaction(sig, {\n rpc,\n rpcSubscriptions: subs as never,\n lastValidBlockHeight: lvbh,\n clock: systemClock,\n onUpdate: (u) => print(`${color.dim(String(u.at))} ${u.state} ${u.detail}`),\n });\n renderWatchTx(result);\n}\n\nexport async function runSimulateCommand(args: ParsedArgs): Promise<void> {\n const name = flagString(args, 'scenario');\n if (!name || flagBool(args, 'list')) {\n print(color.bold('Available scenarios:'));\n for (const s of listScenarios()) print(` ${color.cyan(s.name)} — ${s.description}`);\n return;\n }\n const scenario = SCENARIOS[name];\n if (!scenario) throw new Error(`unknown scenario \"${name}\" (try --list)`);\n\n if (flagBool(args, 'live')) {\n await runSimulateLive(args);\n return;\n }\n\n // Non-live: drive the mock chain + clock with a tick counter (no real sleeps).\n let t = 0;\n await runSimulation(scenario, {\n now: () => t,\n advance: (ms) => {\n t += ms;\n },\n onTick: (tick) => renderSimulationTick(tick),\n });\n print();\n print(color.dim(`scenario \"${scenario.name}\" complete`));\n}\n\n/**\n * The cinematic `--live` view: a paced, scrolling feed of the arc — healthy\n * probes → injected outage (breaker opens, traffic reroutes) → recovery\n * (half-open trial → closed) → a closing health table and the \"0 failed user\n * calls\" thesis. The simulation itself is the deterministic in-process mock, so\n * the data never depends on real latency; only the inter-beat pacing is real\n * (capped, so it stays loop-friendly regardless of host speed).\n */\nasync function runSimulateLive(args: ParsedArgs): Promise<void> {\n const scenario = SCENARIOS[flagString(args, 'scenario')!]!;\n // Pacing per beat, capped to 200–700ms so a viewer can follow without dragging.\n const beatMs = Math.max(200, Math.min(700, flagInt(args, 'beat', 420)));\n\n clearScreen();\n renderSimulationHeader(scenario);\n\n const collected: SimulationTick[] = [];\n // A hybrid clock: the plan timeline is anchored to tick boundaries (`base`), but\n // within a tick `now()` also tracks *real* elapsed time. The chaos transport\n // really sleeps its injected latency, so this lets the SDK's latency EWMA read a\n // realistic number — the bars animate — without perturbing the fault timeline.\n let base = 0;\n let anchor = performance.now();\n await runSimulation(scenario, {\n now: () => base + (performance.now() - anchor),\n advance: (ms) => {\n base += ms;\n anchor = performance.now();\n },\n onTick: (tick) => {\n collected.push(tick);\n },\n });\n\n for (const tick of collected) {\n renderSimulationLiveTick(tick);\n print();\n await sleep(beatMs);\n }\n\n const last = collected[collected.length - 1];\n if (last) renderSimulationSummary(last, summarizeSimulation(collected));\n}\n\nexport async function runMonitorCommand(args: ParsedArgs): Promise<void> {\n const urls = endpointsFromArgs(args);\n const { pool, rpc } = createResilientRpc(urls.map((url) => ({ url })));\n const history: Record<string, number[]> = {};\n const intervalMs = flagInt(args, 'interval', 1000);\n\n const tick = async (): Promise<void> => {\n try {\n await rpc.getSlot().send();\n } catch {\n /* health model absorbs failures */\n }\n const snapshot = pool.getHealthSnapshot();\n for (const h of snapshot) history[h.url] = pushSample(history[h.url] ?? [], h.latencyEwmaMs);\n clearScreen();\n print(color.bold('bastion monitor') + color.dim(' (ctrl-c to exit)'));\n print();\n renderMonitor(summarizeSnapshot(snapshot), history);\n };\n\n await tick();\n const timer = setInterval(() => void tick(), intervalMs);\n // Run until the process is interrupted.\n await new Promise<void>((resolve) => {\n process.on('SIGINT', () => {\n clearInterval(timer);\n resolve();\n });\n });\n}\n\nexport function runHelp(): void {\n print(color.bold('bastion') + ' — Solana RPC/transaction resilience diagnostics');\n print();\n print('Commands:');\n print(` ${color.cyan('doctor')} --endpoints <urls> | --config <file> [--probes N] [--json]`);\n print(` ${color.cyan('monitor')} --endpoints <urls> | --config <file> [--interval ms]`);\n print(` ${color.cyan('watch-tx')} <signature> --endpoints <urls>`);\n print(` ${color.cyan('simulate')} --scenario <name> [--live] | --list`);\n}\n\n/**\n * The CLI entry: parse argv → route → run the handler. Returns the exit code.\n * Lives in the I/O layer (excluded from coverage); the pure `route` it calls is\n * tested in `cli.test.ts`.\n */\nexport async function main(argv: readonly string[]): Promise<number> {\n const { parseArgs } = await import('../data/args');\n const { route } = await import('../cli');\n const args = parseArgs(argv);\n try {\n switch (route(args)) {\n case 'doctor':\n await runDoctorCommand(args);\n break;\n case 'monitor':\n await runMonitorCommand(args);\n break;\n case 'watch-tx':\n await runWatchTxCommand(args);\n break;\n case 'simulate':\n await runSimulateCommand(args);\n break;\n default:\n runHelp();\n }\n return 0;\n } catch (e) {\n console.error(`bastion: ${e instanceof Error ? e.message : String(e)}`);\n return 1;\n }\n}\n","#!/usr/bin/env node\n// The `bastion` executable. All logic lives in the data layer + ui/run; this is\n// just the entrypoint. Excluded from coverage (under no test harness).\nimport { main } from './run';\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (err) => {\n console.error(err);\n process.exitCode = 1;\n },\n);\n"]}