Transactional outbox and publish retries
Implement order creation with an outbox event and the subsequent publication.
`create_order(store, order, event)`:
- `order` is a non-empty order dict;
- `event` is an event dict with a non-empty string `id`, plus `type` and
`payload`;
- the order and the event are written **in one transaction** via
`store.transaction()`;
- if the event write fails, the order must not be saved either;
- return the original event.
`dispatch_pending(store, publish, *, max_attempts=3, limit=100)`:
- takes `store.pending_events(limit)` — events without a publication and without
a dead-letter, in insertion order;
- calls `publish(event)` for each event;
- on success — `store.mark_published(event["id"])`;
- on `PublishError` — `store.record_failure(event["id"], str(error))` returns
the attempt count; once it reaches `max_attempts`, call
`store.mark_dead(event["id"], str(error))`;
- an event with `attempts >= max_attempts` goes to dead-letter immediately,
without another publish;
- other exceptions from `publish` are not caught;
- on a retry the **same** `event["id"]` goes to `publish`: the broker is
idempotent by key, so no duplicate appears.
Return a report:
```python
{"published": 1, "retried": 1, "dead": 0}
```
Store API:
```python
store.transaction() # context manager, commit or rollback
store.add_order(order)
store.add_outbox(event)
store.pending_events(limit) # events with an attempts field (0 for new)
store.mark_published(event_id)
store.record_failure(event_id, error) -> int # attempts after the increment
store.mark_dead(event_id, error)
```
Boundaries:
- `max_attempts < 1` or `limit < 1` — `ValueError`;
- an empty order or an event without `id` — `ValueError` before any write;
- `limit` caps the number of events per pass; the rest stay pending.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
How do you write the order and the event so that a failure loses neither one nor
the other?