Class: Trabox::Publisher::Google::Cloud::PubSub

Inherits:
Object
  • Object
show all
Includes:
Trabox::Publisher
Defined in:
lib/trabox/publisher/google/cloud_pubsub.rb

Defined Under Namespace

Classes: OrderingKey

Constant Summary collapse

LOG_PREFIX =
'[google pubsub]'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(topic_id, message_ordering: true, ordering_key: nil) ⇒ PubSub

Returns a new instance of PubSub.

Parameters:

  • topic_id (String)
  • message_ordering (Boolean) (defaults to: true)

    enable_message_ordering

  • ordering_key (OrderingKey) (defaults to: nil)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/trabox/publisher/google/cloud_pubsub.rb', line 38

def initialize(topic_id, message_ordering: true, ordering_key: nil)
  raise ArgumentError, 'topic_id must be specified.' if topic_id.blank?

  unless ordering_key.nil? || ordering_key.is_a?(OrderingKey)
    raise ArgumentError,
          'ordering_key must be specified OrderingKey class or nil.'
  end

  # @type [Google::Cloud::PubSub::Project]
  @pubsub = ::Google::Cloud::PubSub.new

  # @type [Google::Cloud::PubSub::Topic]
  @topic = @pubsub.topic topic_id

  @ordering_key = ordering_key

  raise "Topic-ID='#{topic_id}' does not exist." if @topic.nil?

  @topic.enable_message_ordering! if message_ordering
rescue StandardError => e
  Rails.logger.error "#{LOG_PREFIX} #{e.message}"
  raise
end

Instance Method Details

#publish(event) ⇒ Object

Parameters:

  • event (ActiveRecord)

    publishするイベント



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/trabox/publisher/google/cloud_pubsub.rb', line 64

def publish(event)
  raise ArgumentError, 'event should be set to trabox:model' unless event.respond_to?(:event_data)

  message = event.event_data

  raise ArgumentError, 'published message must not be blank' if message.blank?

  published_message = if @ordering_key
                        @topic.publish message, ordering_key: @ordering_key.call(event)
                      else
                        @topic.publish message
                      end

  Rails.logger.debug "#{LOG_PREFIX} message published. " \
    "message_id=#{published_message.message_id} ordering_key=#{published_message.ordering_key}"

  published_message.message_id
rescue StandardError => e
  Rails.logger.error "#{LOG_PREFIX} #{e.message}"
  raise
end