Exercise: an idempotent consumer
A payments consumer receives a message and adds its amount to a balance. With at-least-once delivery the same message can arrive again, and then the money is added twice. The broker in this exercise is a model in the tests file, not a real RabbitMQ: the same queue as in the previous exercise, plus the consumer loop consume, which acknowledges a message after calling Handle.
Fill in the Dedup type, the function NewDedup() *Dedup and the method func (d *Dedup) Handle(m Message, apply func(Message) error) error. The function apply performs the message's effect; in the tests, it adds the money.
Dedup follows three rules:
Handlepasses a message with a newIDtoapply, and skips a message whoseIDwas already applied: it does not callapplyand returnsnil;- if
applyreturns an error,Handlereturns that error and does not remember theID, so the message is applied when it is redelivered; - each
Dedupremembers only its own messages.
Example:
- the queue holds
pay-1for100andpay-2for50, and the balance is0; - the consumer applies
pay-1and crashes beforeAck, with the balance already at100; - after
q.Crash(), the messagepay-1arrives again, andHandleskips it; pay-2is applied, and the balance becomes150.
In a real service the set of processed IDs is stored in the database and written in the same transaction as the effect itself: the lesson on exactly-once explains how.
Do not add extra imports unless the task says so explicitly.