Exactly-once: transactions and idempotency
`TransactionalProcessor.process(messages, transform)` processes a batch of
messages and publishes the result so that a redelivery does not create a
duplicate.
`Message` is a dataclass with `key`, `offset` and `value`.
`producer` provides:
- `begin_transaction()`, `commit_transaction()`, `abort_transaction()`;
- `send(key, value)`;
- `committed_keys` — the set of keys already visible to consumers.
`offsets` provides `mark(offset)`, `commit()`, `abort()`.
Rules:
- the transaction opens before the first `send`, and the offset is committed
**only after** a successful `commit_transaction()`;
- on any exception: `abort_transaction()`, `abort()` for offsets, and the
exception propagates;
- a key from `producer.committed_keys` is not sent again, but its offset is
still marked;
- duplicate keys inside one batch are also collapsed: one `send` per key;
- `transform` is called only for the messages that will really go to `send`,
and exactly once per key;
- an empty batch still goes through begin/commit and commits an empty offset
set;
- `process` returns the number of processed messages.
Write tests: a successful batch and the order of operations, a failing
`transform`, a failing `commit_transaction`, a redelivered committed key, a
duplicate inside the batch and an empty batch.
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
In what order should `commit_transaction()` and the offset `commit()` go if the
broker can reject the transaction?