feat(settings): manual replay button for failed webhook deliveries

The deliveries drawer now shows operators a failed delivery + its
payload + the receiver response (b6c3fe80), but offered no action —
they'd have to flip a DB row by hand to retry. This commit closes
the last natural follow-up on the webhook UI loop.

Service:
  - enqueueDeliveryReplay(id) resets attempt_count=0, status='pending',
    response_status/body cleared, next_attempt_at=now. The exp-backoff
    schedule starts fresh — semantics match Stripe's manual-retry
    behaviour ("treat as a brand-new delivery for retry-budget").
  - deliveryBelongsToEndpoint(deliveryId, endpointId) — fail-closed
    ownership check used by the route to avoid leaking deliveries
    across endpoint boundaries.

Route POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay:
  - Supabase session only (integration keys shouldn't be able to nudge
    their own delivery queue — same escalation argument as elsewhere)
  - Authorises via userOwnsEndpoint THEN deliveryBelongsToEndpoint
  - 404 on either mismatch (no probing the endpoint or delivery ID space)
  - 500 on service failure

UI in WebhookDeliveriesDrawer:
  - Replay button rendered in the expanded section above Sent payload
  - Spinning RotateCcw icon during the request, disabled while replaying
  - On success, reloads the deliveries list — the worker may already
    have moved the row by the time the user looks again

47 suites · 610 tests · 0 failures. tsc + eslint clean.

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 01:47:50 +02:00
1 parent b6c3fe807f
commit bfd39b6d8b
3 files changed
+181 -1

No files matched your search

@@ -0,0 +1,72 @@
/**
* POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay
*
* Operator-only manual replay of a single delivery. The /api/cron/
* webhook-worker handles automatic retries with exp-backoff; this
* route is for when an operator looks at a failed delivery in the
* /settings/integrations drawer and wants to nudge it through after
* fixing the receiver.
*
* Auth: Supabase session only (an integration key shouldn't be able
* to influence its own delivery queue — same escalation argument as
* elsewhere). Returns 404 on endpoint OR delivery mismatch to avoid
* leaking either ID space to probers.
*
* Effect: resets attempt_count to 0, status to 'pending',
* next_attempt_at to now. The worker picks it up on the next minute.
*
* Created: 2026-06-04
*/
import { NextRequest } from 'next/server';
import { createServerClient } from '@/lib/supabase/server';
import {
apiSuccess,
apiUnauthorized,
apiNotFound,
apiError,
handleApiError,
} from '@/lib/api/standardResponse';
import { userOwnsEndpoint } from '@/services/webhooks/webhookEndpointsService';
import {
deliveryBelongsToEndpoint,
enqueueDeliveryReplay,
} from '@/services/webhooks/deliveryService';
export async function POST(
_req: NextRequest,
{ params }: { params: Promise<{ id: string; deliveryId: string }> }
) {
try {
const supabase = await createServerClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return apiUnauthorized();
}
const { id: endpointId, deliveryId } = await params;
const owns = await userOwnsEndpoint(endpointId, user.id);
if (!owns) {
return apiNotFound('Webhook endpoint');
}
const belongs = await deliveryBelongsToEndpoint(deliveryId, endpointId);
if (!belongs) {
// Same 404 envelope so probers can't tell endpoint-mismatch from
// delivery-mismatch from never-existed.
return apiNotFound('Webhook delivery');
}
const replayed = await enqueueDeliveryReplay(deliveryId);
if (!replayed) {
return apiError('Replay failed', 'INTERNAL_ERROR', 500);
}
return apiSuccess({ replayed: true });
} catch (error) {
return handleApiError(error);
}
}
@@ -13,7 +13,15 @@
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { CheckCircle2, ChevronDown, ChevronRight, Clock, RefreshCw, XCircle } from 'lucide-react';
import {
CheckCircle2,
ChevronDown,
ChevronRight,
Clock,
RefreshCw,
RotateCcw,
XCircle,
} from 'lucide-react';
import { logger } from '@/utils/logger';
interface DeliveryRow {
@@ -80,6 +88,7 @@ export default function WebhookDeliveriesDrawer({ endpointId }: Props) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [expandedId, setExpandedId] = useState<string | null>(null);
const [replayingId, setReplayingId] = useState<string | null>(null);
const cancelRef = useRef(false);
const load = useCallback(async () => {
@@ -109,6 +118,31 @@ export default function WebhookDeliveriesDrawer({ endpointId }: Props) {
}
}, [endpointId]);
const handleReplay = useCallback(
async (deliveryId: string) => {
setReplayingId(deliveryId);
setError(null);
try {
const res = await fetch(
`/api/webhook-endpoints/${endpointId}/deliveries/${deliveryId}/replay`,
{ method: 'POST', credentials: 'include' }
);
if (!res.ok) {
const body = (await res.json().catch(() => null)) as { error?: string } | null;
throw new Error(body?.error || `Failed to replay (${res.status})`);
}
// Reload — the row's status, attempt_count, next_attempt_at all
// changed and the worker may already have moved it.
await load();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to replay');
} finally {
setReplayingId(null);
}
},
[endpointId, load]
);
useEffect(() => {
load();
return () => {
@@ -183,6 +217,19 @@ export default function WebhookDeliveriesDrawer({ endpointId }: Props) {
</button>
{isExpanded && (
<div className="mt-2 ml-5 space-y-2">
<div className="flex justify-end">
<button
type="button"
onClick={() => handleReplay(d.id)}
disabled={replayingId === d.id}
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2 py-1 text-[11px] text-muted-foreground hover:bg-muted/60 hover:text-foreground disabled:opacity-50"
>
<RotateCcw
className={`h-3 w-3 ${replayingId === d.id ? 'animate-spin' : ''}`}
/>
{replayingId === d.id ? 'Replaying…' : 'Replay'}
</button>
</div>
<div>
<div className="mb-1 text-[10px] uppercase tracking-wide text-muted-foreground">
Sent payload
+61
View File
@@ -256,6 +256,67 @@ export async function pruneDeliveredWebhookDeliveries(
return count ?? 0;
}
/**
* Confirm a delivery row belongs to the given endpoint. Used by the
* replay route to avoid leaking deliveries across endpoint boundaries.
* Returns false on mismatch + on any DB error (fail-closed).
*/
export async function deliveryBelongsToEndpoint(
deliveryId: string,
endpointId: string
): Promise<boolean> {
const admin = createAdminClient();
const { data, error } = await admin
.from(DATABASE_TABLES.WEBHOOK_DELIVERIES)
.select('id')
.eq('id', deliveryId)
.eq('endpoint_id', endpointId)
.maybeSingle();
if (error) {
logger.warn('deliveryBelongsToEndpoint: query failed', { error, deliveryId, endpointId });
return false;
}
return !!data;
}
/**
* Manually re-enqueue a delivery. Wipes response_status + response_body
* so the next worker run starts clean, resets attempt_count to 0 (the
* exp-backoff schedule starts fresh), flips status back to 'pending',
* and schedules next_attempt_at=now so the next /api/cron/webhook-worker
* tick (every minute) picks it up.
*
* The user-facing semantics are "treat this as a brand-new delivery
* for retry-budget purposes." That keeps the contract obvious in the
* UI ("Replay" button) and matches how Stripe + similar platforms
* surface manual retries.
*
* The caller MUST have already verified the delivery belongs to an
* endpoint the requesting user owns — this function trusts ownership.
*/
export async function enqueueDeliveryReplay(deliveryId: string): Promise<boolean> {
const admin = createAdminClient();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data, error } = await (admin.from(DATABASE_TABLES.WEBHOOK_DELIVERIES) as any)
.update({
status: 'pending',
attempt_count: 0,
response_status: null,
response_body: null,
last_attempt_at: null,
next_attempt_at: new Date().toISOString(),
})
.eq('id', deliveryId)
.select('id')
.maybeSingle();
if (error) {
logger.error('enqueueDeliveryReplay failed', { error, deliveryId });
return false;
}
return !!data;
}
export async function markFailedOrRetry(
delivery: DeliveryRow,
responseStatus: number | null,