@@ -165,6 +165,56 @@ mkMessage k v = ProducerRecord
165
165
}
166
166
```
167
167
168
+ ### Synchronous sending of messages
169
+ Because of the asynchronous nature of librdkafka. It there is no API to provide
170
+ synchronous production of messages. It is, however, possible to combine the
171
+ delivery reports feature with that of callbacks. This can be done using the
172
+ ` Kafka.Producer.produceMessage' ` function.
173
+
174
+ ``` haskell
175
+ produceMessage' :: MonadIO m
176
+ => KafkaProducer
177
+ -> ProducerRecord
178
+ -> (DeliveryReport -> IO () )
179
+ -> m (Either ImmediateError () )
180
+ ```
181
+
182
+ Using this function, you can provide a callback which will be invoked upon the
183
+ produced message's delivery report. With a little help of `MVar `s or similar,
184
+ you can in fact, create a synchronous- like interface.
185
+
186
+ ```haskell
187
+ sendMessageSync :: MonadIO m
188
+ => KafkaProducer
189
+ -> ProducerRecord
190
+ -> m (Either KafkaError Offset )
191
+ sendMessageSync producer record = liftIO $ do
192
+ -- Create an empty MVar:
193
+ var <- newEmptyMVar
194
+
195
+ -- Produce the message and use the callback to put the delivery report in the
196
+ -- MVar:
197
+ res <- produceMessage' producer record (putMVar var)
198
+
199
+ case res of
200
+ Left (ImmediateError err) ->
201
+ pure (Left err)
202
+ Right () -> do
203
+ -- Flush producer queue to make sure you don't get stuck waiting for the
204
+ -- message to send:
205
+ flushProducer producer
206
+
207
+ -- Wait for the message's delivery report and map accordingly:
208
+ takeMVar var >>= return . \ case
209
+ DeliverySuccess _ offset -> Right offset
210
+ DeliveryFailure _ err -> Left err
211
+ NoMessageError err -> Left err
212
+ ```
213
+
214
+ _ Note:_ this is a semi-naive solution as this waits forever (or until
215
+ librdkafka times out). You should make sure that your configuration reflects
216
+ the behavior you want out of this functionality.
217
+
168
218
# Installation
169
219
170
220
## Installing librdkafka
0 commit comments