test(api): lock GET /api/cron/webhook-worker branches

The most state-touching route on the platform. Vercel cron runs this
every minute; silent regressions in processDelivery silently drop
customer deliveries — they see "0 deliveries" with no signal until
they complain. Last remaining untested platform route.

12 tests across 5 sections:

Auth (2):
  - 401 no header (pickDueDeliveries verified NOT called)
  - 401 wrong secret (same assertion)

Empty batch (1):
  - processed:0 returned; fetch + claim verified NOT called

processDelivery branches (7) — each delivery row exercises one branch:
  - skipped: claimDelivery returns false → no further work, summary
    has only skipped++, getEndpointSigningContext + fetch + mark*
    verified NOT called
  - delivered (revoked): signing-context null → markDelivered called
    with (id, 0, '[endpoint revoked]'); fetch + touchEndpoint NOT called
  - delivered (2xx): POST with all 4 X-OrangeCat-* headers asserted
    (Signature from signWebhookPayload, Event-Id, Event-Type,
    Content-Type); markDelivered called with response body; touchEndpoint
    called with endpoint_id; markFailedOrRetry NOT called
  - retry (non-2xx under MAX): markFailedOrRetry called with
    claimedDelivery (attempt_count=3 after bump), response status,
    body; markDelivered NOT called; summary.retry++
  - failed (non-2xx after MAX): attempt_count=6 input bumps to 7
    (>MAX_ATTEMPTS) → summary.failed++ instead of retry; verifies
    the matching boundary fix from eb5fc998
  - retry (network error): markFailedOrRetry with (null,
    '[network] ECONNRESET'); summary.retry++
  - retry (non-Error network rejection): String() coerced to '[network] unknown'

Top-level error (1):
  - 500 INTERNAL_ERROR when pickDueDeliveries throws

Batch summary (1):
  - 3 deliveries, mixed outcomes (delivered + skipped + retry):
    summary aggregates correctly, processed:3; apiSuccess called
    with full summary shape

Mock pattern: all four services + signing + global fetch + logger
mocked at module-import level; CRON_SECRET set per-test in beforeEach,
deleted in afterAll; per-delivery defaults in beforeEach so tests
opt into delivery rows via pickDueDeliveries override.

Suite: 54 suites · 701 tests · 0 failures. tsc + eslint clean.
All untested platform routes now covered.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-04 03:03:20 +02:00
1 parent 8f9f184158
commit 5f051a83a6
1 file changed
+334
@@ -0,0 +1,334 @@
/**
* GET /api/cron/webhook-worker — handler-level branch tests.
*
* Vercel cron runs this every minute. Silent failures in processDelivery
* drop deliveries on the floor; customers see "0 deliveries" with no
* signal, and OrangeCat operators don't notice until a customer complains.
*
* The worker is the most-state-touching route on the platform: claim
* (atomic), signing-context fetch, sign, fetch the customer URL, branch
* on response status, log + mark + bump for retry. Each branch matters.
*
* Created: 2026-06-04
*/
jest.mock('@/utils/logger', () => ({
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('@/services/webhooks/deliveryService', () => ({
pickDueDeliveries: jest.fn(),
claimDelivery: jest.fn(),
markDelivered: jest.fn(),
markFailedOrRetry: jest.fn(),
}));
jest.mock('@/services/webhooks/webhookEndpointsService', () => ({
getEndpointSigningContext: jest.fn(),
touchEndpointLastDelivery: jest.fn(),
}));
jest.mock('@/services/webhooks/signing', () => ({
signWebhookPayload: jest.fn(() => 't=1700000000,v1=stub'),
}));
jest.mock('@/lib/api/standardResponse', () => ({
apiSuccess: jest.fn((payload: unknown) => ({ ok: true, data: payload, status: 200 })),
apiError: jest.fn((msg: string, code: string, status: number) => ({
ok: false,
error: msg,
code,
status,
})),
apiUnauthorized: jest.fn(() => ({ ok: false, error: 'Unauthorized', status: 401 })),
}));
import { GET } from '@/app/api/cron/webhook-worker/route';
import {
pickDueDeliveries,
claimDelivery,
markDelivered,
markFailedOrRetry,
} from '@/services/webhooks/deliveryService';
import {
getEndpointSigningContext,
touchEndpointLastDelivery,
} from '@/services/webhooks/webhookEndpointsService';
import { signWebhookPayload } from '@/services/webhooks/signing';
import { apiSuccess, apiUnauthorized } from '@/lib/api/standardResponse';
const CRON_SECRET = 'test-cron-secret';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function makeRequest(authHeader: string | null): any {
return {
headers: {
get: (name: string) => (name.toLowerCase() === 'authorization' ? authHeader : null),
},
};
}
function makeDelivery(overrides: Partial<{ id: string; attempt_count: number }> = {}) {
return {
id: 'd-1',
endpoint_id: 'e-1',
event_type: 'product.created',
event_id: 'evt-1',
payload: { hello: 'world' },
status: 'pending' as const,
response_status: null,
response_body: null,
attempt_count: 0,
last_attempt_at: null,
next_attempt_at: new Date().toISOString(),
created_at: new Date().toISOString(),
...overrides,
};
}
const goodCtx = {
url: 'https://recv.example/hook',
secret: 'ock_whk_test_secret_value',
actorId: 'a-1',
};
beforeEach(() => {
jest.clearAllMocks();
process.env.CRON_SECRET = CRON_SECRET;
// Default to "auth + empty batch" so tests opt into delivery rows.
(pickDueDeliveries as jest.Mock).mockResolvedValue([]);
(claimDelivery as jest.Mock).mockResolvedValue(true);
(getEndpointSigningContext as jest.Mock).mockResolvedValue(goodCtx);
(markDelivered as jest.Mock).mockResolvedValue(undefined);
(markFailedOrRetry as jest.Mock).mockResolvedValue(undefined);
// Default global fetch — tests override per case.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).fetch = jest.fn();
});
afterAll(() => {
delete process.env.CRON_SECRET;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (global as any).fetch;
});
// =============================================================================
// Auth
// =============================================================================
describe('GET /api/cron/webhook-worker — auth', () => {
it('returns 401 when no authorization header', async () => {
const res = (await GET(makeRequest(null))) as { status: number };
expect(res.status).toBe(401);
expect(apiUnauthorized).toHaveBeenCalled();
expect(pickDueDeliveries).not.toHaveBeenCalled();
});
it('returns 401 when secret does not match', async () => {
const res = (await GET(makeRequest('Bearer wrong'))) as { status: number };
expect(res.status).toBe(401);
expect(pickDueDeliveries).not.toHaveBeenCalled();
});
});
// =============================================================================
// Empty batch
// =============================================================================
describe('GET /api/cron/webhook-worker — empty batch', () => {
it('returns processed:0 when nothing is due', async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([]);
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
ok: boolean;
data: { processed: number; ranAt: string };
};
expect(res.ok).toBe(true);
expect(res.data.processed).toBe(0);
expect(typeof res.data.ranAt).toBe('string');
expect(global.fetch).not.toHaveBeenCalled();
expect(claimDelivery).not.toHaveBeenCalled();
});
});
// =============================================================================
// processDelivery branches — each delivery row exercises one branch.
// =============================================================================
describe('GET /api/cron/webhook-worker — processDelivery branches', () => {
it('skipped: claim returns false → no further work, summary.skipped++', async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery()]);
(claimDelivery as jest.Mock).mockResolvedValue(false);
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { processed: number; summary: Record<string, number> };
};
expect(res.data.processed).toBe(1);
expect(res.data.summary).toEqual({ delivered: 0, retry: 0, failed: 0, skipped: 1 });
expect(getEndpointSigningContext).not.toHaveBeenCalled();
expect(global.fetch).not.toHaveBeenCalled();
expect(markDelivered).not.toHaveBeenCalled();
expect(markFailedOrRetry).not.toHaveBeenCalled();
});
it("delivered (revoked): signing context is null → markDelivered(0, '[endpoint revoked]')", async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery()]);
(getEndpointSigningContext as jest.Mock).mockResolvedValue(null);
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { summary: Record<string, number> };
};
expect(res.data.summary.delivered).toBe(1);
expect(markDelivered).toHaveBeenCalledWith('d-1', 0, '[endpoint revoked]');
expect(global.fetch).not.toHaveBeenCalled();
expect(touchEndpointLastDelivery).not.toHaveBeenCalled();
});
it('delivered (2xx): POSTs with signature + headers, markDelivered, touchEndpoint fires', async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery()]);
(global.fetch as jest.Mock).mockResolvedValue({
status: 204,
text: () => Promise.resolve(''),
});
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { summary: Record<string, number> };
};
expect(res.data.summary.delivered).toBe(1);
expect(signWebhookPayload).toHaveBeenCalledWith(
JSON.stringify({ hello: 'world' }),
goodCtx.secret
);
expect(global.fetch).toHaveBeenCalledTimes(1);
const [calledUrl, init] = (global.fetch as jest.Mock).mock.calls[0];
expect(calledUrl).toBe(goodCtx.url);
expect(init.method).toBe('POST');
expect(init.headers['Content-Type']).toBe('application/json');
expect(init.headers['X-OrangeCat-Signature']).toBe('t=1700000000,v1=stub');
expect(init.headers['X-OrangeCat-Event-Id']).toBe('evt-1');
expect(init.headers['X-OrangeCat-Event-Type']).toBe('product.created');
expect(markDelivered).toHaveBeenCalledWith('d-1', 204, '');
expect(touchEndpointLastDelivery).toHaveBeenCalledWith('e-1');
expect(markFailedOrRetry).not.toHaveBeenCalled();
});
it('retry (non-2xx, under MAX): markFailedOrRetry with response status + body', async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery({ attempt_count: 2 })]);
(global.fetch as jest.Mock).mockResolvedValue({
status: 503,
text: () => Promise.resolve('try again'),
});
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { summary: Record<string, number> };
};
expect(res.data.summary.retry).toBe(1);
expect(markFailedOrRetry).toHaveBeenCalledWith(
expect.objectContaining({ id: 'd-1', attempt_count: 3 }), // claim bumped
503,
'try again'
);
expect(markDelivered).not.toHaveBeenCalled();
});
it('failed (non-2xx, after MAX attempts): summary.failed++ instead of retry', async () => {
// attempt_count starts at 6 → claim bumps to 7 → 7 > 6 → outcome 'failed'
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery({ attempt_count: 6 })]);
(global.fetch as jest.Mock).mockResolvedValue({
status: 500,
text: () => Promise.resolve(''),
});
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { summary: Record<string, number> };
};
expect(res.data.summary.failed).toBe(1);
expect(res.data.summary.retry).toBe(0);
expect(markFailedOrRetry).toHaveBeenCalled();
});
it("retry (network error): markFailedOrRetry(null, '[network] <msg>'), null responseStatus", async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery({ attempt_count: 2 })]);
(global.fetch as jest.Mock).mockRejectedValue(new Error('ECONNRESET'));
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { summary: Record<string, number> };
};
expect(res.data.summary.retry).toBe(1);
expect(markFailedOrRetry).toHaveBeenCalledWith(
expect.objectContaining({ attempt_count: 3 }),
null,
'[network] ECONNRESET'
);
});
it("retry (non-Error network rejection): markFailedOrRetry with '[network] unknown'", async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([makeDelivery()]);
(global.fetch as jest.Mock).mockRejectedValue('weird');
await GET(makeRequest(`Bearer ${CRON_SECRET}`));
expect(markFailedOrRetry).toHaveBeenCalledWith(expect.anything(), null, '[network] unknown');
});
});
// =============================================================================
// Top-level error path
// =============================================================================
describe('GET /api/cron/webhook-worker — top-level error', () => {
it('returns 500 INTERNAL_ERROR when pickDueDeliveries throws', async () => {
(pickDueDeliveries as jest.Mock).mockRejectedValue(new Error('db gone'));
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as { status: number };
expect(res.status).toBe(500);
});
});
// =============================================================================
// Batch summary across multiple deliveries
// =============================================================================
describe('GET /api/cron/webhook-worker — batch summary', () => {
it('aggregates outcomes across deliveries in one batch', async () => {
(pickDueDeliveries as jest.Mock).mockResolvedValue([
makeDelivery({ id: 'd-1' }),
makeDelivery({ id: 'd-2' }),
makeDelivery({ id: 'd-3' }),
]);
(claimDelivery as jest.Mock)
.mockResolvedValueOnce(true) // d-1 claims
.mockResolvedValueOnce(false) // d-2 skipped
.mockResolvedValueOnce(true); // d-3 claims
(global.fetch as jest.Mock)
.mockResolvedValueOnce({ status: 200, text: () => Promise.resolve('ok') }) // d-1 delivered
.mockResolvedValueOnce({ status: 500, text: () => Promise.resolve('bad') }); // d-3 retry
const res = (await GET(makeRequest(`Bearer ${CRON_SECRET}`))) as {
data: { processed: number; summary: Record<string, number> };
};
expect(res.data.processed).toBe(3);
expect(res.data.summary).toEqual({ delivered: 1, retry: 1, failed: 0, skipped: 1 });
// apiSuccess includes the ranAt timestamp from the wrapping success payload.
expect(apiSuccess).toHaveBeenCalledWith(
expect.objectContaining({
processed: 3,
summary: { delivered: 1, retry: 1, failed: 0, skipped: 1 },
})
);
});
});