tidaldb/tests/e2e/support/cluster.ts
jordan 15f6b11187 test(e2e): Playwright evidence harness for the deploy-verification runbook
Turns docs/runbooks/deploy-verification.md from prose into 32 executable checks
against the live orchard9-k3sf cluster, and it found real defects on its first
run — including in the runbook it verifies.

WHY PLAYWRIGHT, HONESTLY
tidalDB serves zero HTML (no text/html, no Html(), 10 JSON routes), so this uses
Playwright in three distinct roles rather than pretending there is a UI:
  * request fixture as a real HTTP client for DNS/TLS/auth/quorum/404;
  * a browser for the only genuine screens in the chain, Grafana;
  * a test harness for cluster-plane checks with no HTTP surface, shelling out
    to kubectl and attaching the real transcript as evidence.

WHAT IT CAUGHT
  * The runbook asserted the operator/data credential split was "not active yet
    - requires an image roll". globalSetup read the live image and the live
    secret; a probe returned data->403, admin->200. It had been enforcing the
    whole time. Section 9 rewritten. (BUG-001)
  * docs/ops/grafana-tidaldb.json shipped datasource uid ${DS_PROMETHEUS} - a
    Grafana export-for-sharing placeholder with no __inputs block to resolve it.
    Under ConfigMap provisioning every panel queried a datasource that did not
    exist, so the whole board was blank. The API said "loaded" and I had only
    ever checked the API. 41 refs fixed here, 58 across the fleet ConfigMap,
    which was also blanking the postgres and redis dashboards. (BUG-007)
  * Stat panels used calcs "lastNonNull". Grafana's reducer is "lastNotNull", so
    no value was ever computed and Cluster health / Reseed pending / Indexed
    vectors rendered as empty boxes. I chased panel width and then panel height
    before comparing against a working stat panel elsewhere in the same Grafana.
    A spelling error wearing a layout bug's clothes. (BUG-009)
  * The namespace variable defaulted to All, so cluster panels silently included
    tidaldb-586b544c8-vpkmw from the superseded standalone deployment. Latency
    legends read "p50 p50 p50" with no way to tell the nodes apart. Both fixed.
  * "5xx ratio" rendered "No data" as large green text - at a glance a healthy
    value. And Fleet state gave three fields one shared green threshold, so
    reseed_required=1 would have shown GREEN during the exact incident the panel
    exists to surface. Split into three panels with per-field mappings.
  * tidalctl cluster-status exits 2 on a FULLY CONVERGED cluster, because the
    aggregated endpoint reports healthy peers as region=null applied=0
    reachable=false. The runbook claimed `cluster-status && deploy` was a safe
    gate; that claim came from an exit code masked by a shell pipeline. The gate
    can never pass here. Documented, test pins it, engine defect recorded.
    (BUG-005)
  * The deployed image writes ANSI colour into container logs, which the
    collector stores verbatim. Already fixed in logging.rs, not yet rolled;
    pinned as a tripwire. (BUG-006)
  * The runbook's own backup command sorted ALL backups by timestamp and
    selected a restore-canary run: 20 items, one volume, a meaningless pass.
    Now filters on the schedule label the freshness alert actually watches.

DEFECTS FOUND BY LOOKING AT THE SCREENS
Six of the first eight captures were slop and were fixed, not promoted:
230-350px of dead space; a verdict that rendered "exit code 2" in green; the
1600x1800 dashboard scaled into 16:9 until illegible (now clipped to the
evidence band using real element bounds); the dream beat whose caption described
a contradiction the image did not show (now a purpose-built capture holding the
committed doc text, the running image, and the live 403/200 side by side); and a
one-frame blink to bare background at every scene boundary, because Remotion
Sequences do not overlap and both scenes sat at opacity 0 on the boundary frame.

TRIPWIRES IN THE HONEST DIRECTION
Three tests assert what is ABSENT - zero tidaldb_http_* families, JSON_LOGS
unset, plain-text logs - and each carries the message "good news, roll the
runbook section from pending to live". The metric-absence test also asserts the
baseline family count, so "absent" cannot pass for "the scrape failed". That is
the drift that made section 9 stale in the first place.

Regression config uses workers:1 and retries:0 deliberately: a live-cluster
check that only passes on the second attempt has told you something true.

Verified: 32 passed (46.8s); 9 demo captures each asserting before photographing;
tsc clean; render 82.05s 1920x1080 h264, 0 empty frames across 10 boundaries;
every promoted image inspected individually and judged perfect; walk-the-render
ledger complete with no fails.
2026-08-23 14:03:29 -06:00

228 lines
6.9 KiB
TypeScript

/**
* Cluster-plane access for checks that have no HTTP surface.
*
* tidalDB serves JSON only — it has no operator web UI — and pod readiness,
* NetworkPolicy enforcement, container logs, and Velero state are not reachable
* over HTTP at all. Those checks shell out to kubectl. That is a deliberate,
* documented choice: the alternative is inventing an HTTP surface that does not
* exist and asserting against a fiction.
*
* Everything here returns real captured output for attachment as evidence, with
* secrets redacted on the way out.
*/
import { execFile, spawn, type ChildProcess } from 'node:child_process';
import { createConnection } from 'node:net';
import { setTimeout as sleep } from 'node:timers/promises';
import { promisify } from 'node:util';
import { KUBECONFIG, TIDALCTL_BIN, redact } from './env';
const execFileAsync = promisify(execFile);
export type CommandResult = {
/** argv as run, for the evidence record. */
command: string;
code: number;
stdout: string;
stderr: string;
};
const DEFAULT_TIMEOUT_MS = 30_000;
/**
* Run a binary with no shell. Never throws on a non-zero exit — the caller
* asserts on `code`, so a failing command is evidence rather than a crash.
*/
export async function run(
file: string,
args: string[],
options: { timeoutMs?: number; env?: Record<string, string> } = {},
): Promise<CommandResult> {
const command = redact([file, ...args].join(' '));
try {
const { stdout, stderr } = await execFileAsync(file, args, {
timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
maxBuffer: 32 * 1024 * 1024,
env: { ...process.env, KUBECONFIG, ...options.env },
});
return { command, code: 0, stdout: redact(stdout), stderr: redact(stderr) };
} catch (error) {
const err = error as {
code?: number | string;
stdout?: string;
stderr?: string;
message: string;
};
return {
command,
code: typeof err.code === 'number' ? err.code : 1,
stdout: redact(err.stdout ?? ''),
stderr: redact(err.stderr ?? err.message),
};
}
}
/** Run kubectl with the pinned kubeconfig. */
export async function kubectl(
args: string[],
options: { timeoutMs?: number } = {},
): Promise<CommandResult> {
return run('kubectl', args, options);
}
/** Run kubectl and fail loudly — for prerequisites, where a failure is fatal. */
export async function kubectlOrThrow(args: string[]): Promise<string> {
const result = await kubectl(args);
if (result.code !== 0) {
throw new Error(
`kubectl failed (exit ${result.code}): ${result.command}\n${result.stderr}`,
);
}
return result.stdout;
}
/** Run the built tidalctl binary. */
export async function tidalctl(
args: string[],
options: { timeoutMs?: number } = {},
): Promise<CommandResult> {
return run(TIDALCTL_BIN, args, options);
}
/**
* Resolve one Secret key to plaintext. Used only to source credentials into the
* suite; the value is registered for redaction and never attached.
*/
export async function secretValue(
namespace: string,
secret: string,
key: string,
): Promise<string | undefined> {
const result = await kubectl([
'-n',
namespace,
'get',
'secret',
secret,
'-o',
`jsonpath={.data.${key}}`,
]);
if (result.code !== 0 || result.stdout.trim() === '') return undefined;
return Buffer.from(result.stdout.trim(), 'base64').toString('utf8');
}
/** True once something accepts a TCP connection on the port. */
async function portAccepts(port: number, host = '127.0.0.1'): Promise<boolean> {
const { promise, resolve } = Promise.withResolvers<boolean>();
const socket = createConnection({ port, host });
const settle = (ok: boolean) => {
socket.destroy();
resolve(ok);
};
socket.setTimeout(1_000);
socket.once('connect', () => settle(true));
socket.once('timeout', () => settle(false));
socket.once('error', () => settle(false));
return promise;
}
export type PortForward = {
localPort: number;
target: string;
close: () => Promise<void>;
};
/**
* Ports are allocated from a high base and bumped per acquisition so parallel
* workers never collide. Playwright workers are separate processes, so the
* worker index is folded into the base.
*/
let portCursor = 0;
const PORT_BASE = 19_600;
const WORKER_STRIDE = 40;
/**
* Open a port-forward and wait until the local port actually accepts a
* connection.
*
* The manual runbook tells a human to `sleep 8` because a shorter wait races
* kubectl's bind and returns an empty body that reads exactly like a dead node.
* A harness can do better than a fixed sleep: poll until the port answers, then
* proceed. Faster when the bind is quick, and it cannot produce that false
* negative when the cluster is slow.
*/
export async function portForward(
namespace: string,
target: string,
remotePort: number,
options: { timeoutMs?: number } = {},
): Promise<PortForward> {
const workerIndex = Number.parseInt(process.env.TEST_PARALLEL_INDEX ?? '0', 10);
const localPort = PORT_BASE + workerIndex * WORKER_STRIDE + portCursor;
portCursor = (portCursor + 1) % WORKER_STRIDE;
const timeoutMs = options.timeoutMs ?? 30_000;
const child: ChildProcess = spawn(
'kubectl',
['-n', namespace, 'port-forward', target, `${localPort}:${remotePort}`],
{ env: { ...process.env, KUBECONFIG }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let exitInfo: string | undefined;
let stderr = '';
child.stderr?.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
});
child.once('exit', (code, signal) => {
exitInfo = `kubectl port-forward exited early (code=${code} signal=${signal}): ${stderr.trim()}`;
});
const close = async () => {
if (child.exitCode !== null || child.signalCode !== null) return;
const { promise, resolve } = Promise.withResolvers<void>();
const hardKill = setTimeout(() => {
child.kill('SIGKILL');
resolve();
}, 3_000);
child.once('exit', () => {
clearTimeout(hardKill);
resolve();
});
child.kill('SIGTERM');
await promise;
};
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (exitInfo) {
await close();
throw new Error(`${exitInfo}\ntarget: ${namespace}/${target}:${remotePort}`);
}
if (await portAccepts(localPort)) {
return { localPort, target: `${namespace}/${target}:${remotePort}`, close };
}
await sleep(250);
}
await close();
throw new Error(
`port-forward to ${namespace}/${target}:${remotePort} never accepted a connection ` +
`on 127.0.0.1:${localPort} within ${timeoutMs}ms.\nkubectl stderr: ${stderr.trim()}`,
);
}
/** Run `body` against an open port-forward and always tear it down. */
export async function withPortForward<T>(
namespace: string,
target: string,
remotePort: number,
body: (forward: PortForward) => Promise<T>,
): Promise<T> {
const forward = await portForward(namespace, target, remotePort);
try {
return await body(forward);
} finally {
await forward.close();
}
}