/ opencodehub / src / pages / api / cron / notification-digests.ts
swadhinbiswas Add digest delivery retries and observability metrics · 2/19/2026
4b685b4
50 lines · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import type { APIRoute } from "astro";
import { runDueDigests } from "@/lib/chat-notifications";
import { logger } from "@/lib/logger";

const CRON_SECRET = process.env.CRON_SECRET;

function isAuthorized(request: Request): boolean {
    if (!CRON_SECRET) return false;
    const authHeader = request.headers.get("Authorization");
    return authHeader === `Bearer ${CRON_SECRET}`;
}

export const POST: APIRoute = async ({ request, url }) => {
    if (!isAuthorized(request)) {
        return new Response("Unauthorized", { status: 401 });
    }

    const dryRun = url.searchParams.get("dryRun") === "true";
    const rawMaxRetries = url.searchParams.get("maxRetries");
    const parsedMaxRetries = rawMaxRetries ? Number.parseInt(rawMaxRetries, 10) : 1;
    const maxRetries = Number.isNaN(parsedMaxRetries) ? 1 : parsedMaxRetries;

    try {
        const result = await runDueDigests({ dryRun, maxRetries });
        logger.info({ dryRun, maxRetries, ...result }, "Notification digest cron completed");

        return new Response(JSON.stringify({
            success: true,
            dryRun,
            maxRetries,
            ...result,
        }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
        });
    } catch (error) {
        const message = error instanceof Error ? error.message : "Unknown error";
        logger.error({ error: message, dryRun, maxRetries }, "Notification digest cron failed");
        return new Response(JSON.stringify({
            success: false,
            error: message,
        }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
        });
    }
};

export const GET = POST;