Class: JetstreamBridge::BatchPublisher

Inherits:
Object
  • Object
show all
Defined in:
lib/jetstream_bridge/publisher/batch_publisher.rb

Overview

Batch publisher for efficient bulk event publishing.

BatchPublisher allows you to queue multiple events and publish them together, providing detailed results about successes and failures. Each event is published independently, so partial failures are possible.

Examples:

Publishing multiple events

results = JetstreamBridge.publish_batch do |batch|
  users.each do |user|
    batch.add(event_type: "user.created", payload: { id: user.id })
  end
end

puts "Published: #{results.successful_count}, Failed: #{results.failed_count}"
results.errors.each { |e| logger.error("Failed: #{e[:event_id]}") }

Checking for failures

results = JetstreamBridge.publish_batch do |batch|
  batch.add(event_type: "order.created", payload: { id: 1 })
  batch.add(event_type: "order.updated", payload: { id: 2 })
end

if results.failure?
  logger.warn "Some events failed to publish"
end

Defined Under Namespace

Classes: BatchResult

Instance Method Summary collapse

Constructor Details

#initialize(publisher = nil) ⇒ BatchPublisher



99
100
101
102
# File 'lib/jetstream_bridge/publisher/batch_publisher.rb', line 99

def initialize(publisher = nil)
  @publisher = publisher || Publisher.new
  @events = []
end

Instance Method Details

#add(event_or_hash = nil, resource_type: nil, event_type: nil, payload: nil, **options) ⇒ self

Add an event to the batch



112
113
114
115
116
117
118
119
120
121
# File 'lib/jetstream_bridge/publisher/batch_publisher.rb', line 112

def add(event_or_hash = nil, resource_type: nil, event_type: nil, payload: nil, **options)
  @events << {
    event_or_hash: event_or_hash,
    resource_type: resource_type,
    event_type: event_type,
    payload: payload,
    options: options
  }
  self
end

#empty?Boolean



159
160
161
# File 'lib/jetstream_bridge/publisher/batch_publisher.rb', line 159

def empty?
  @events.empty?
end

#publishBatchResult

Publish all events in the batch



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/jetstream_bridge/publisher/batch_publisher.rb', line 126

def publish
  results = @events.map do |event_data|
    @publisher.publish(
      event_data[:event_or_hash],
      resource_type: event_data[:resource_type],
      event_type: event_data[:event_type],
      payload: event_data[:payload],
      **event_data[:options]
    )
  rescue StandardError => e
    Models::PublishResult.new(
      success: false,
      event_id: 'unknown',
      subject: 'unknown',
      error: e
    )
  end

  BatchResult.new(results)
ensure
  @events.clear
end

#sizeInteger Also known as: count, length

Get number of events queued



152
153
154
# File 'lib/jetstream_bridge/publisher/batch_publisher.rb', line 152

def size
  @events.size
end