harb/tests/setup/stack.ts

119 lines
3.5 KiB
TypeScript
Raw Normal View History

import { exec as execCallback } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
feat: Add functional health checks for test prerequisites (#65) Replaces basic "service is up" checks with functional verification that tests can actually use the services. ## Changes ### New Health Checks - **RPC Proxy**: Verifies eth_call works and deployed contracts are accessible - **GraphQL**: Confirms Ponder has indexed data with non-zero stats - **Web App**: Validates endpoint accessibility ### Improvements - Clear error messages explain what failed and how to fix it - Checks verify actual functionality, not just HTTP 200 responses - Fails fast before tests run with cryptic errors ### Files - `tests/setup/health-checks.ts` - Core health check functions - `tests/setup/stack.ts` - Integration with waitForStackReady() - `tests/HEALTH_CHECKS.md` - Documentation and troubleshooting guide ## Error Message Example Before: ``` RPC health check failed with status 404 ``` After: ``` ❌ Stack health check failed Failed services: • RPC Proxy: RPC proxy returned HTTP 404 Expected 200, got 404. Check if Anvil is running and RPC_URL is correct. • GraphQL Indexer: GraphQL has no indexed data yet Ponder is running but has not indexed contract events. Troubleshooting: 1. Check stack logs: tail tests/.stack.log 2. Verify services are running: ./scripts/dev.sh status 3. Restart stack: ./scripts/dev.sh restart --full ``` ## Benefits - ✅ Tests fail fast with clear error messages - ✅ Catches configuration issues before tests run - ✅ Verifies services are actually usable, not just running resolves #61 Co-authored-by: johba <johba@harb.eth> Reviewed-on: https://codeberg.org/johba/harb/pulls/65
2025-10-05 20:03:07 +02:00
import {
runAllHealthChecks,
formatHealthCheckError,
type HealthCheckResult,
} from './health-checks.js';
const exec = promisify(execCallback);
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const repoRoot = resolve(__dirname, '..', '..');
const DEFAULT_RPC_URL = process.env.STACK_RPC_URL ?? 'http://127.0.0.1:8545';
const DEFAULT_WEBAPP_URL = process.env.STACK_WEBAPP_URL ?? 'http://localhost:5173';
const DEFAULT_GRAPHQL_URL = process.env.STACK_GRAPHQL_URL ?? 'http://localhost:42069/graphql';
let stackStarted = false;
async function cleanupContainers(): Promise<void> {
try {
await run("podman pod ps -q --filter name=harb | xargs -r podman pod rm -f || true");
await run("podman ps -aq --filter name=harb | xargs -r podman rm -f || true");
} catch (error) {
console.warn('[stack] Failed to cleanup containers', error);
}
}
function delay(ms: number): Promise<void> {
return new Promise(resolveDelay => setTimeout(resolveDelay, ms));
}
async function run(command: string): Promise<void> {
await exec(command, { cwd: repoRoot, shell: true });
}
feat: Add functional health checks for test prerequisites (#65) Replaces basic "service is up" checks with functional verification that tests can actually use the services. ## Changes ### New Health Checks - **RPC Proxy**: Verifies eth_call works and deployed contracts are accessible - **GraphQL**: Confirms Ponder has indexed data with non-zero stats - **Web App**: Validates endpoint accessibility ### Improvements - Clear error messages explain what failed and how to fix it - Checks verify actual functionality, not just HTTP 200 responses - Fails fast before tests run with cryptic errors ### Files - `tests/setup/health-checks.ts` - Core health check functions - `tests/setup/stack.ts` - Integration with waitForStackReady() - `tests/HEALTH_CHECKS.md` - Documentation and troubleshooting guide ## Error Message Example Before: ``` RPC health check failed with status 404 ``` After: ``` ❌ Stack health check failed Failed services: • RPC Proxy: RPC proxy returned HTTP 404 Expected 200, got 404. Check if Anvil is running and RPC_URL is correct. • GraphQL Indexer: GraphQL has no indexed data yet Ponder is running but has not indexed contract events. Troubleshooting: 1. Check stack logs: tail tests/.stack.log 2. Verify services are running: ./scripts/dev.sh status 3. Restart stack: ./scripts/dev.sh restart --full ``` ## Benefits - ✅ Tests fail fast with clear error messages - ✅ Catches configuration issues before tests run - ✅ Verifies services are actually usable, not just running resolves #61 Co-authored-by: johba <johba@harb.eth> Reviewed-on: https://codeberg.org/johba/harb/pulls/65
2025-10-05 20:03:07 +02:00
/**
* Run functional health checks that verify services are actually usable, not just running
*/
async function checkStackFunctional(
rpcUrl: string,
webAppUrl: string,
graphqlUrl: string
): Promise<void> {
const results = await runAllHealthChecks({ rpcUrl, webAppUrl, graphqlUrl });
const failures = results.filter(r => !r.success);
if (failures.length > 0) {
throw new Error(formatHealthCheckError(results));
}
}
export async function startStack(): Promise<void> {
if (stackStarted) {
return;
}
await cleanupContainers();
await run('nohup ./scripts/dev.sh start > ./tests/.stack.log 2>&1 &');
stackStarted = true;
}
export async function waitForStackReady(options: {
rpcUrl?: string;
webAppUrl?: string;
graphqlUrl?: string;
timeoutMs?: number;
pollIntervalMs?: number;
} = {}): Promise<void> {
const rpcUrl = options.rpcUrl ?? DEFAULT_RPC_URL;
const webAppUrl = options.webAppUrl ?? DEFAULT_WEBAPP_URL;
const graphqlUrl = options.graphqlUrl ?? DEFAULT_GRAPHQL_URL;
const timeoutMs = options.timeoutMs ?? 180_000;
const pollIntervalMs = options.pollIntervalMs ?? 2_000;
const start = Date.now();
const errors = new Map<string, string>();
while (Date.now() - start < timeoutMs) {
try {
feat: Add functional health checks for test prerequisites (#65) Replaces basic "service is up" checks with functional verification that tests can actually use the services. ## Changes ### New Health Checks - **RPC Proxy**: Verifies eth_call works and deployed contracts are accessible - **GraphQL**: Confirms Ponder has indexed data with non-zero stats - **Web App**: Validates endpoint accessibility ### Improvements - Clear error messages explain what failed and how to fix it - Checks verify actual functionality, not just HTTP 200 responses - Fails fast before tests run with cryptic errors ### Files - `tests/setup/health-checks.ts` - Core health check functions - `tests/setup/stack.ts` - Integration with waitForStackReady() - `tests/HEALTH_CHECKS.md` - Documentation and troubleshooting guide ## Error Message Example Before: ``` RPC health check failed with status 404 ``` After: ``` ❌ Stack health check failed Failed services: • RPC Proxy: RPC proxy returned HTTP 404 Expected 200, got 404. Check if Anvil is running and RPC_URL is correct. • GraphQL Indexer: GraphQL has no indexed data yet Ponder is running but has not indexed contract events. Troubleshooting: 1. Check stack logs: tail tests/.stack.log 2. Verify services are running: ./scripts/dev.sh status 3. Restart stack: ./scripts/dev.sh restart --full ``` ## Benefits - ✅ Tests fail fast with clear error messages - ✅ Catches configuration issues before tests run - ✅ Verifies services are actually usable, not just running resolves #61 Co-authored-by: johba <johba@harb.eth> Reviewed-on: https://codeberg.org/johba/harb/pulls/65
2025-10-05 20:03:07 +02:00
await checkStackFunctional(rpcUrl, webAppUrl, graphqlUrl);
console.log('✅ All stack health checks passed');
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
errors.set('lastError', message);
await delay(pollIntervalMs);
}
}
const logPath = resolve(repoRoot, 'tests', '.stack.log');
let logTail = '';
try {
const contents = await readFile(logPath, 'utf-8');
logTail = contents.split('\n').slice(-40).join('\n');
} catch (readError) {
logTail = `Unable to read stack log: ${readError}`;
}
throw new Error(`Stack failed to become ready within ${timeoutMs}ms\nLast error: ${errors.get('lastError')}\nLog tail:\n${logTail}`);
}
export async function stopStack(): Promise<void> {
if (!stackStarted) {
return;
}
try {
await run('./scripts/dev.sh stop');
} finally {
stackStarted = false;
}
}