Module: WaterDrop::Producer::Async

Included in:
WaterDrop::Producer
Defined in:
lib/waterdrop/producer/async.rb

Overview

Component for asynchronous producer operations

Instance Method Summary collapse

Instance Method Details

#produce_async(message) ⇒ Rdkafka::Producer::DeliveryHandle

Produces a message to Kafka and does not wait for results

Parameters:

Returns:

  • (Rdkafka::Producer::DeliveryHandle)

    delivery handle that might return the report

Raises:

  • (Rdkafka::RdkafkaError)

    When adding the message to rdkafka’s queue failed

  • (Errors::MessageInvalidError)

    When provided message details are invalid and the message could not be sent to Kafka



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/waterdrop/producer/async.rb', line 16

def produce_async(message)
  message = middleware.run(message)
  validate_message!(message)

  @monitor.instrument(
    'message.produced_async',
    producer_id: id,
    message: message
  ) { produce(message) }
rescue *SUPPORTED_FLOW_ERRORS => e
  # We use this syntax here because we want to preserve the original `#cause` when we
  # instrument the error and there is no way to manually assign `#cause` value
  begin
    raise Errors::ProduceError, e.inspect
  rescue Errors::ProduceError => ex
    @monitor.instrument(
      'error.occurred',
      producer_id: id,
      message: message,
      error: ex,
      type: 'message.produce_async'
    )

    raise ex
  end
end

#produce_many_async(messages) ⇒ Array<Rdkafka::Producer::DeliveryHandle>

Produces many messages to Kafka and does not wait for them to be delivered

Parameters:

  • messages (Array<Hash>)

    array with messages that comply with the Contracts::Message contract

Returns:

  • (Array<Rdkafka::Producer::DeliveryHandle>)

    deliveries handles

Raises:

  • (Rdkafka::RdkafkaError)

    When adding the messages to rdkafka’s queue failed

  • (Errors::MessageInvalidError)

    When any of the provided messages details are invalid and the message could not be sent to Kafka



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/waterdrop/producer/async.rb', line 53

def produce_many_async(messages)
  dispatched = []
  messages = middleware.run_many(messages)
  messages.each { |message| validate_message!(message) }

  @monitor.instrument(
    'messages.produced_async',
    producer_id: id,
    messages: messages
  ) do
    with_transaction_if_transactional do
      messages.each do |message|
        dispatched << produce(message)
      end
    end

    dispatched
  end
rescue *SUPPORTED_FLOW_ERRORS => e
  re_raised = Errors::ProduceManyError.new(dispatched, e.inspect)

  @monitor.instrument(
    'error.occurred',
    producer_id: id,
    messages: messages,
    dispatched: dispatched,
    error: re_raised,
    type: 'messages.produce_many_async'
  )

  raise re_raised
end