# Webhook receiver with dedupe and sync log

A FastAPI app that accepts POST /webhook with an event ID and a
payload, processes each event ID once, and writes a sync log row per
event in SQLite. Each row carries a status (pending, synced, or
failed), an attempt count, and the last error. A repeat delivery of a
synced event returns a duplicate result without reprocessing. A
repeat delivery of a failed event retries the downstream step and
increments the attempt count.

## Run

```bash
cd ~/freelance-engine/projects/dev-artefacts/webhook-receiver
~/freelance-engine/.venv/bin/python -m uvicorn app:app --port 8011
```

The database path defaults to sync.db in this directory. Set
WEBHOOK_DB to change it.

## Try it

```bash
curl -s -X POST localhost:8011/webhook \
  -H 'content-type: application/json' \
  -d '{"event_id": "evt-1", "payload": {"name": "Sam"}}'

# Same event again: returns duplicate, no second processing
curl -s -X POST localhost:8011/webhook \
  -H 'content-type: application/json' \
  -d '{"event_id": "evt-1", "payload": {"name": "Sam"}}'

# Downstream failure stub: payload with "fail": true
curl -s -X POST localhost:8011/webhook \
  -H 'content-type: application/json' \
  -d '{"event_id": "evt-2", "payload": {"fail": true}}'

curl -s localhost:8011/sync-log
```

Sample responses:

```json
{"event_id": "evt-1", "status": "synced", "attempts": 1}
{"event_id": "evt-1", "status": "duplicate", "attempts": 1}
```

The failed event returns HTTP 502 and its log row shows status
failed with attempts 1. Posting evt-2 again without the fail flag
retries and lands at synced with attempts 2.

## Tests

```bash
~/freelance-engine/.venv/bin/python -m pytest tests/ -q
```

Covers first POST syncing, duplicate POST deduping with a counting
processor proving one downstream call, failed downstream marking the
row failed and a retry syncing at attempt 2, invalid payloads
returning 422 with no log rows, and the health endpoint.

## Verification log

- 2026-11-19: test suite run from a clean shell, 5 passed.
- The downstream step is a stub that fails only on "fail": true in
  the payload. Swap process_event in app.py for a real API call and
  the dedupe, retry state, and log behavior carry over unchanged.
