Skip to content
Exercise · Delivery guarantees · lesson 4 of 9

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 and true, or false when 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 the Redelivered flag;
  • 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 process never returns an error, every message is processed and acknowledged, and the function returns nil;
  • if process returns 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 to ConsumeAll gets the message that failed again and finishes the job, so no message is lost.

Example:

  • the queue holds m1, m2, m3, and process returns an error once on m2;
  • the first call processes and acknowledges m1, stops at m2 and returns the error from process;
  • q.Crash() puts m2 back at the front of the queue, before m3;
  • the second call processes m2 and m3 and returns nil.

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.

consume.go — go
go · 6 lines
Ctrl+Enter run · Esc leave editor