Class: Gcloud::Pubsub::Topic

Inherits:
Object
  • Object
show all
Defined in:
lib/gcloud/pubsub/topic.rb,
lib/gcloud/pubsub/topic/list.rb

Overview

Topic

A named resource to which messages are published.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
topic.publish "task completed"

Defined Under Namespace

Classes: Batch, List

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTopic

Create an empty Topic object.



47
48
49
50
51
52
53
# File 'lib/gcloud/pubsub/topic.rb', line 47

def initialize #:nodoc:
  @connection = nil
  @gapi = {}
  @name = nil
  @autocreate = nil
  @exists = nil
end

Instance Attribute Details

#connectionObject

The Connection object.



39
40
41
# File 'lib/gcloud/pubsub/topic.rb', line 39

def connection
  @connection
end

#gapiObject

The Google API Client object.



43
44
45
# File 'lib/gcloud/pubsub/topic.rb', line 43

def gapi
  @gapi
end

Class Method Details

.from_gapi(gapi, conn) ⇒ Object

New Topic from a Google API Client object.



540
541
542
543
544
545
# File 'lib/gcloud/pubsub/topic.rb', line 540

def self.from_gapi gapi, conn #:nodoc:
  new.tap do |f|
    f.gapi = gapi
    f.connection = conn
  end
end

.new_lazy(name, conn, options = {}) ⇒ Object

New lazy Topic object without making an HTTP request.



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/gcloud/pubsub/topic.rb', line 57

def self.new_lazy name, conn, options = {} #:nodoc:
  options[:autocreate] = true if options[:autocreate].nil?
  new.tap do |t|
    t.gapi = nil
    t.connection = conn
    t.instance_eval do
      @name = conn.topic_path(name, options)
      @autocreate = options[:autocreate]
    end
  end
end

Instance Method Details

#autocreate?Boolean

Determines whether the lazy topic object should create a topic on the Pub/Sub service.

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
topic.autocreate? #=> true

Returns:

  • (Boolean)


532
533
534
# File 'lib/gcloud/pubsub/topic.rb', line 532

def autocreate? #:nodoc:
  @autocreate
end

#deleteObject

Permanently deletes the topic.

Returns

true if the topic was deleted.

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
topic.delete


93
94
95
96
97
98
99
100
101
# File 'lib/gcloud/pubsub/topic.rb', line 93

def delete
  ensure_connection!
  resp = connection.delete_topic name
  if resp.success?
    true
  else
    fail ApiError.from_response(resp)
  end
end

#exists?Boolean

Determines whether the topic exists in the Pub/Sub service.

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
topic.exists? #=> true

Returns:

  • (Boolean)


489
490
491
492
493
494
495
496
# File 'lib/gcloud/pubsub/topic.rb', line 489

def exists?
  # Always true if we have a gapi object
  return true unless @gapi.nil?
  # If we have a value, return it
  return @exists unless @exists.nil?
  ensure_gapi!
  @exists = !@gapi.nil?
end

#get_subscription(subscription_name) ⇒ Object Also known as: find_subscription

Retrieves a subscription by name. The difference between this method and Topic#subscription is that this method makes an API call to Pub/Sub to verify the subscription exists.

Parameters

subscription_name

Name of a subscription. (String)

Returns

Gcloud::Pubsub::Subscription or nil if subscription does not exist

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
subscription = topic.get_subscription "my-topic-subscription"
puts subscription.name


235
236
237
238
239
240
241
242
243
# File 'lib/gcloud/pubsub/topic.rb', line 235

def get_subscription subscription_name
  ensure_connection!
  resp = connection.get_subscription subscription_name
  if resp.success?
    Subscription.from_gapi resp.data, connection
  else
    nil
  end
end

#lazy?Boolean

Determines whether the topic object was created with an HTTP call.

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
topic.lazy? #=> false

Returns:

  • (Boolean)


511
512
513
# File 'lib/gcloud/pubsub/topic.rb', line 511

def lazy? #:nodoc:
  @gapi.nil?
end

#nameObject

The name of the topic in the form of “/projects/project-identifier/topics/topic-name”.



72
73
74
# File 'lib/gcloud/pubsub/topic.rb', line 72

def name
  @gapi ? @gapi["name"] : @name
end

#policy(options = {}) ⇒ Object

Gets the access control policy.

Parameters

options

An optional Hash for controlling additional behavior. (Hash)

options[:force]

Force the latest policy to be retrieved from the Pub/Sub service when +true. Otherwise the policy will be memoized to reduce the number of API calls made to the Pub/Sub service. The default is false. (Boolean)

Returns

A hash that conforms to the following structure:

{
  "bindings" => [{
    "role" => "roles/viewer",
    "members" => ["serviceAccount:your-service-account"]
  }],
  "rules" => []
}

Examples

By default, the policy values are memoized to reduce the number of API calls to the Pub/Sub service.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
puts topic.policy["bindings"]
puts topic.policy["rules"]

To retrieve the latest policy from the Pub/Sub service, use the force flag.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
policy = topic.policy force: true


422
423
424
425
426
427
428
429
430
431
# File 'lib/gcloud/pubsub/topic.rb', line 422

def policy options = {}
  @policy = nil if options[:force]
  @policy ||= begin
    ensure_connection!
    resp = connection.get_topic_policy name
    policy = resp.data["policy"]
    policy = policy.to_hash if policy.respond_to? :to_hash
    policy
  end
end

#policy=(new_policy) ⇒ Object

Sets the access control policy.

Parameters

new_policy

A hash that conforms to the following structure:

{
  "bindings" => [{
    "role" => "roles/viewer",
    "members" => ["serviceAccount:your-service-account"]
  }],
  "rules" => []
}

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

viewer_policy = {
  "bindings" => [{
    "role" => "roles/viewer",
    "members" => ["serviceAccount:your-service-account"]
  }]
}
topic = pubsub.topic "my-topic"
topic.policy = viewer_policy


465
466
467
468
469
470
471
472
473
474
# File 'lib/gcloud/pubsub/topic.rb', line 465

def policy= new_policy
  ensure_connection!
  resp = connection.set_topic_policy name, new_policy
  if resp.success?
    @policy = resp.data["policy"]
    @policy = @policy.to_hash if @policy.respond_to? :to_hash
  else
    fail ApiError.from_response(resp)
  end
end

#publish(data = nil, attributes = {}) ⇒ Object

Publishes one or more messages to the topic.

Parameters

data

The message data. (String)

attributes

Optional attributes for the message. (Hash)

Returns

Message object when called without a block, Array of Message objects when called with a block

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
msg = topic.publish "new-message"

Additionally, a message can be published with attributes:

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
msg = topic.publish "new-message",
                    foo: :bar,
                    this: :that

Multiple messages can be published at the same time by passing a block:

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
msgs = topic.publish do |batch|
  batch.publish "new-message-1", foo: :bar
  batch.publish "new-message-2", foo: :baz
  batch.publish "new-message-3", foo: :bif
end


361
362
363
364
365
366
367
368
369
370
# File 'lib/gcloud/pubsub/topic.rb', line 361

def publish data = nil, attributes = {}
  ensure_connection!
  batch = Batch.new data, attributes
  yield batch if block_given?
  return nil if batch.messages.count.zero?
  publish_batch_messages batch
rescue Gcloud::Pubsub::NotFoundError => e
  retry if lazily_create_topic!
  raise e
end

#subscribe(subscription_name, options = {}) ⇒ Object Also known as: create_subscription, new_subscription

Creates a new Subscription object on the current Topic.

Parameters

subscription_name

Name of the new subscription. Must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with “goog”. (String)

options

An optional Hash for controlling additional behavior. (Hash)

options[:deadline]

The maximum number of seconds after a subscriber receives a message before the subscriber should acknowledge the message. (Integer)

options[:endpoint]

A URL locating the endpoint to which messages should be pushed. e.g. “example.com/push” (String)

Returns

Gcloud::Pubsub::Subscription

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
sub = topic.subscribe "my-topic-sub"
puts sub.name # => "my-topic-sub"

The name is optional, and will be generated if not given.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
sub = topic.subscribe "my-topic-sub"
puts sub.name # => "generated-sub-name"

The subscription can be created that waits two minutes for acknowledgement and pushed all messages to an endpoint

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
sub = topic.subscribe "my-topic-sub",
                      deadline: 120,
                      endpoint: "https://example.com/push"


162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/gcloud/pubsub/topic.rb', line 162

def subscribe subscription_name, options = {}
  ensure_connection!
  resp = connection.create_subscription name, subscription_name, options
  if resp.success?
    Subscription.from_gapi resp.data, connection
  else
    fail ApiError.from_response(resp)
  end
rescue Gcloud::Pubsub::NotFoundError => e
  retry if lazily_create_topic!
  raise e
end

#subscription(subscription_name) ⇒ Object

Retrieves subscription by name. The difference between this method and Topic#get_subscription is that this method does not make an API call to Pub/Sub to verify the subscription exists.

Parameters

subscription_name

Name of a subscription. (String)

Returns

Gcloud::Pubsub::Subscription

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
subscription = topic.subscription "my-topic-subscription"
puts subscription.name


203
204
205
206
207
# File 'lib/gcloud/pubsub/topic.rb', line 203

def subscription subscription_name
  ensure_connection!

  Subscription.new_lazy subscription_name, connection
end

#subscriptions(options = {}) ⇒ Object Also known as: find_subscriptions, list_subscriptions

Retrieves a list of subscription names for the given project.

Parameters

options

An optional Hash for controlling additional behavior. (Hash)

options[:token]

The token value returned by the last call to subscriptions; indicates that this is a continuation of a call, and that the system should return the next page of data. (String)

options[:max]

Maximum number of subscriptions to return. (Integer)

Returns

Array of Subscription objects (Subscription::List)

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
subscription = topic.subscriptions
subscriptions.each do |subscription|
  puts subscription.name
end

If you have a significant number of subscriptions, you may need to paginate through them: (See Subscription::List#token)

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
all_subs = []
tmp_subs = topic.subscriptions
while tmp_subs.any? do
  tmp_subs.each do |subscription|
    all_subs << subscription
  end
  # break loop if no more subscriptions available
  break if tmp_subs.token.nil?
  # get the next group of subscriptions
  tmp_subs = topic.subscriptions token: tmp_subs.token
end


298
299
300
301
302
303
304
305
306
# File 'lib/gcloud/pubsub/topic.rb', line 298

def subscriptions options = {}
  ensure_connection!
  resp = connection.list_topics_subscriptions name, options
  if resp.success?
    Subscription::List.from_resp resp, connection
  else
    fail ApiError.from_response(resp)
  end
end