Exercise: acknowledge after the work
A consumer takes messages from a queue and saves each one to a database. If the database is down, the message must not be lost: the consumer stops, and after a restart the broker delivers the message again. The broker in this exercise is a model in the tests file, not a real RabbitMQ: a queue with manual acknowledgements that, like RabbitMQ, puts unacknowledged messages back.
The model has five methods:
q.Next()hands out the next message andtrue, orfalsewhen the queue is empty;q.Ack(id)acknowledges a message, and the broker deletes it for good;q.Crash()simulates a consumer crash: unacknowledged messages return to the front of the queue with theRedeliveredflag;q.Ready()counts the messages waiting to be handed out;q.Unacked()counts the messages handed out but not acknowledged.
Write the function func ConsumeAll(q *Queue, process func(Message) error) error. It takes messages from q until the queue is empty and passes each one to process.
The tests check three properties of the function:
- if
processnever returns an error, every message is processed and acknowledged, and the function returnsnil; - if
processreturns an error, the function stops at once: it does not acknowledge that message, takes no further message and returns that error; - after
q.Crash(), the next call toConsumeAllgets the message that failed again and finishes the job, so no message is lost.
Example:
- the queue holds
m1,m2,m3, andprocessreturns an error once onm2; - the first call processes and acknowledges
m1, stops atm2and returns the error fromprocess; q.Crash()putsm2back at the front of the queue, beforem3;- the second call processes
m2andm3and returnsnil.
The model and the checks are on the tests tab: you can read them but not change them.
Do not add extra imports unless the task says so explicitly.