Files
ukmesh/scripts/full-dev/alert-bootstrap.mjs
T

41 lines
2.1 KiB
JavaScript

import { setTimeout as sleep } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
export async function bootstrapAlertReceiver(origin, token, { attempts = 120, intervalMs = 500 } = {}) {
let probeSubmitted = false;
let detail = 'receiver readiness is unavailable';
for (let attempt = 0; attempt < attempts; attempt++) {
try {
const ready = await fetch(`${origin}/readyz`, { signal: AbortSignal.timeout(3000) });
if (ready.ok) return;
const health = await ready.json();
if (health.unresolved_dead_letter_count > 0) {
detail = `${health.unresolved_dead_letter_count} unresolved dead letter(s) require redrive`;
} else if (health.detail === 'no successful forward recorded' && health.pending_count === 0 && !probeSubmitted) {
// An ambiguous response may already have committed the probe. The receiver owns its retries.
probeSubmitted = true;
detail = 'waiting for first successful forward';
const probe = await fetch(`${origin}/alerts`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
signal: AbortSignal.timeout(3000),
body: JSON.stringify({ source: 'local-dev', status: 'resolved', check: 'local forwarding bootstrap' }),
});
if (probe.status !== 202) detail = `bootstrap probe returned HTTP ${probe.status}`;
// The receiver explicitly rejected a durable enqueue, so a later retry can submit again.
if (probe.status === 503) probeSubmitted = false;
} else if (!probeSubmitted) {
detail = health.pending_count > 0 ? 'waiting for queued alert delivery' : 'receiver is not ready';
}
} catch {
if (!probeSubmitted) detail = 'receiver readiness is unavailable';
}
if (attempt + 1 < attempts) await sleep(intervalMs);
}
throw new Error(`Local alert forwarding did not become ready (${detail})`);
}
if (fileURLToPath(import.meta.url) === process.argv[1]) {
await bootstrapAlertReceiver('http://alert-receiver:8080', process.env.ALERT_RECEIVER_TOKEN);
}