Node.js
A wrapper for any async function. The example gives every delivery of a Stripe webhook event its own run.
const base = process.env.DRUMBEATS_MONITOR_URL!;
// A failed or slow ping must not fail the job.
const ping = (event: string, runId: string, error?: string) =>
fetch(`${base}/${event}?run_id=${encodeURIComponent(runId)}`, {
method: error ? 'POST' : 'GET',
headers: error ? { 'Content-Type': 'application/json' } : {},
body: error ? JSON.stringify({ payload: error }) : undefined,
signal: AbortSignal.timeout(3000),
}).catch(() => {});
export async function monitored<T>(
runId: string,
job: () => Promise<T>,
): Promise<T> {
await ping('start', runId);
try {
const result = await job();
await ping('success', runId);
return result;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await ping('failure', runId, message);
throw err;
}
}
app.post('/webhooks/stripe', async (req, res) => {
// Stripe redelivers an event under the same id, so the id alone
// is not a run id: the timestamp keeps each delivery apart.
const runId = `${req.body.id}-${Date.now()}`;
try {
await monitored(runId, () => handleStripeEvent(req.body));
res.sendStatus(200);
} catch {
// monitored() has sent the failure ping and rethrown. Answer,
// or the request hangs until Stripe times out.
res.sendStatus(500);
}
});const base = process.env.DRUMBEATS_MONITOR_URL!;
// A failed or slow ping must not fail the job.
const ping = (event: string, runId: string, error?: string) =>
fetch(`${base}/${event}?run_id=${encodeURIComponent(runId)}`, {
method: error ? 'POST' : 'GET',
headers: error ? { 'Content-Type': 'application/json' } : {},
body: error ? JSON.stringify({ payload: error }) : undefined,
signal: AbortSignal.timeout(3000),
}).catch(() => {});
export async function monitored<T>(
runId: string,
job: () => Promise<T>,
): Promise<T> {
await ping('start', runId);
try {
const result = await job();
await ping('success', runId);
return result;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await ping('failure', runId, message);
throw err;
}
}
app.post('/webhooks/stripe', async (req, res) => {
// Stripe redelivers an event under the same id, so the id alone
// is not a run id: the timestamp keeps each delivery apart.
const runId = `${req.body.id}-${Date.now()}`;
try {
await monitored(runId, () => handleStripeEvent(req.body));
res.sendStatus(200);
} catch {
// monitored() has sent the failure ping and rethrown. Answer,
// or the request hangs until Stripe times out.
res.sendStatus(500);
}
});