// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini import { compose, docker, dockerOk } from './docker'; import { dig } from './dig'; import { containerName, GROUP_NAMES, GROUPS, ORIGIN2_URL, type GroupConfig } from './env'; import { HarnessError } from './errors'; import { initDatabases, waitForMysql } from './mysql'; import { pollUntil } from './proc'; export const STACK_SERVICES = ['mysql', 'coredns', 'origin2', ...GROUP_NAMES.map((g) => GROUPS[g].service)]; export async function waitHealth(group: GroupConfig, timeoutMs = 90_000): Promise { await pollUntil( `${group.service} /health`, async () => { const res = await fetch(`${group.baseURL}/health`, { signal: AbortSignal.timeout(3000) }); const body = await res.text(); return res.status === 200 && body.trim() === '{"status":"ok"}'; }, timeoutMs, 500, ); } export async function waitDns(group: GroupConfig, timeoutMs = 60_000): Promise { await pollUntil(`coredns port ${group.dnsPort}`, async () => (await dig(group, 'probe.invalid.', 'A')).rcode !== '', timeoutMs, 500); } export async function stackUp(log: (s: string) => void = () => undefined): Promise { const started = Date.now(); await compose(['up', '--detach', '--wait', '--wait-timeout', '240', 'mysql'], { timeoutMs: 300_000 }); await waitForMysql(); await initDatabases(); log(`mysql ready and initialized after ${Date.now() - started} ms`); const rest = STACK_SERVICES.filter((s) => s !== 'mysql'); try { await compose(['up', '--detach', '--wait', '--wait-timeout', '240', ...rest], { timeoutMs: 300_000 }); } catch (e) { const logs = await Promise.all(rest.map(async (s) => `--- ${s}\n${(await docker(['logs', '--tail', '40', containerName(s)])).stderr}`)); throw new HarnessError('prerequisite', `stack services did not become healthy: ${(e as Error).message}\n${logs.join('\n')}`); } for (const name of GROUP_NAMES) { await waitHealth(GROUPS[name]); await waitDns(GROUPS[name]); } await pollUntil('second origin', async () => (await fetch(`${ORIGIN2_URL}/health`, { signal: AbortSignal.timeout(3000) })).status === 200, 60_000, 500); log(`stack ready after ${Date.now() - started} ms`); } export async function stackDown(): Promise { await compose(['rm', '--stop', '--force', '--volumes', ...STACK_SERVICES], { timeoutMs: 180_000 }); } export async function restartApp(group: GroupConfig): Promise { await dockerOk(['restart', '--time', '25', containerName(group.service)], { timeoutMs: 120_000 }); await waitHealth(group); } export async function appLogs(group: GroupConfig): Promise { const r = await docker(['logs', containerName(group.service)], { timeoutMs: 60_000 }); return r.stdout + r.stderr; } export async function staticHash(group: GroupConfig): Promise { const res = await fetch(`${group.baseURL}/login`); const html = await res.text(); const m = /\/static\/([0-9a-f]+)\/css\/app\.css/.exec(html); if (!m) throw new HarnessError('protocol', 'no static hash in the login page'); return m[1]; }