Class: Gcloud::Pubsub::Project

Inherits:
Object
  • Object
show all
Defined in:
lib/gcloud/pubsub/project.rb

Overview

Project

Represents the project that pubsub messages are pushed to and pulled from. Topic is a named resource to which messages are sent by publishers. Subscription is a named resource representing the stream of messages from a single, specific topic, to be delivered to the subscribing application. Message is a combination of data and attributes that a publisher sends to a topic and is eventually delivered to subscribers.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

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

See Gcloud#pubsub

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(project, credentials) ⇒ Project

Creates a new Connection instance.



50
51
52
53
54
# File 'lib/gcloud/pubsub/project.rb', line 50

def initialize project, credentials #:nodoc:
  project = project.to_s # Always cast to a string
  fail ArgumentError, "project is missing" if project.empty?
  @connection = Connection.new project, credentials
end

Instance Attribute Details

#connectionObject

The Connection object.



46
47
48
# File 'lib/gcloud/pubsub/project.rb', line 46

def connection
  @connection
end

Class Method Details

.default_projectObject

Default project.



74
75
76
77
78
79
# File 'lib/gcloud/pubsub/project.rb', line 74

def self.default_project #:nodoc:
  ENV["PUBSUB_PROJECT"] ||
    ENV["GCLOUD_PROJECT"] ||
    ENV["GOOGLE_CLOUD_PROJECT"] ||
    Gcloud::GCE.project_id
end

Instance Method Details

#create_topic(topic_name) ⇒ Object Also known as: new_topic

Creates a new topic.

Parameters

topic_name

Name of a topic. (String)

Returns

Gcloud::Pubsub::Topic

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub
topic = pubsub.create_topic "my-topic"


186
187
188
189
190
191
192
193
194
# File 'lib/gcloud/pubsub/project.rb', line 186

def create_topic topic_name
  ensure_connection!
  resp = connection.create_topic topic_name
  if resp.success?
    Topic.from_gapi resp.data, connection
  else
    fail ApiError.from_response(resp)
  end
end

#projectObject

The Pub/Sub project connected to.

Example

require "gcloud"

gcloud = Gcloud.new "my-todo-project",
                    "/path/to/keyfile.json"
pubsub = gcloud.pubsub

pubsub.project #=> "my-todo-project"


68
69
70
# File 'lib/gcloud/pubsub/project.rb', line 68

def project
  connection.project
end

#publish(topic_name, data = nil, attributes = {}) {|batch| ... } ⇒ Object

Publishes one or more messages to the given topic.

Parameters

topic_name

Name of a topic. (String)

data

The message data. (String)

attributes

Optional attributes for the message. (Hash)

attributes[:autocreate]

Flag to control whether the provided topic will be created if it does not exist.

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

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

Additionally, a message can be published with attributes:

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

msg = pubsub.publish "my-topic", "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

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

Additionally, the topic will be created if the topic does previously not exist and the autocreate option is provided.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

msg = pubsub.publish "new-topic", "new-message", autocreate: true

A note about auto-creating the topic: Any message published to a topic without a subscription will be lost.

Yields:

  • (batch)


323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/gcloud/pubsub/project.rb', line 323

def publish topic_name, data = nil, attributes = {}
  # Fix parameters
  if data.is_a?(::Hash) && attributes.empty?
    attributes = data
    data = nil
  end
  # extract autocreate option
  autocreate = attributes.delete :autocreate
  ensure_connection!
  batch = Topic::Batch.new data, attributes
  yield batch if block_given?
  return nil if batch.messages.count.zero?
  publish_batch_messages topic_name, batch, autocreate
end

#subscribe(topic_name, subscription_name, deadline: nil, endpoint: nil, autocreate: nil) ⇒ Object Also known as: create_subscription, new_subscription

Creates a new Subscription object for the provided topic.

Parameters

topic_name

Name of a topic. (String)

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)

deadline

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

endpoint

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

autocreate

Flag to control whether the topic will be created if it does not exist.

Returns

Gcloud::Pubsub::Subscription

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

sub = pubsub.subscribe "my-topic", "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

sub = pubsub.subscribe "my-topic"
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

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

Additionally, the topic will be created if the topic does previously not exist and the autocreate option is provided.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

sub = pubsub.subscribe "new-topic", "new-topic-sub", autocreate: true


407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/gcloud/pubsub/project.rb', line 407

def subscribe topic_name, subscription_name, deadline: nil, endpoint: nil,
              autocreate: nil
  ensure_connection!
  options = { deadline: deadline, endpoint: endpoint }
  resp = connection.create_subscription topic_name,
                                        subscription_name, options
  return Subscription.from_gapi(resp.data, connection) if resp.success?
  if autocreate && resp.status == 404
    create_topic topic_name
    return subscribe(topic_name, subscription_name,
                     deadline: deadline, endpoint: endpoint,
                     autocreate: false)
  end
  fail ApiError.from_response(resp)
end

#subscription(subscription_name, project: nil, skip_lookup: nil) ⇒ Object Also known as: get_subscription, find_subscription

Retrieves subscription by name.

Parameters

subscription_name

Name of a subscription. (String)

project

If the subscription belongs to a project other than the one currently connected to, the alternate project ID can be specified here. (String)

skip_lookup

Optionally create a Subscription object without verifying the subscription resource exists on the Pub/Sub service. Calls made on this object will raise errors if the service resource does not exist. Default is false. (Boolean)

Returns

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

Example

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

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

The lookup against the Pub/Sub service can be skipped using the skip_lookup option:

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

# No API call is made to retrieve the subscription information.
subscription = pubsub.subscription "my-sub", skip_lookup: true
puts subscription.name


468
469
470
471
472
473
474
475
476
477
478
# File 'lib/gcloud/pubsub/project.rb', line 468

def subscription subscription_name, project: nil, skip_lookup: nil
  ensure_connection!
  options = { project: project }
  if skip_lookup
    return Subscription.new_lazy(subscription_name, connection, options)
  end
  resp = connection.get_subscription subscription_name
  return Subscription.from_gapi(resp.data, connection) if resp.success?
  return nil if resp.status == 404
  fail ApiError.from_response(resp)
end

#subscriptions(prefix: nil, token: nil, max: nil) ⇒ Object Also known as: find_subscriptions, list_subscriptions

Retrieves a list of subscriptions for the given project.

Parameters

prefix

Filter results to subscriptions whose names begin with this prefix. (String)

token

A previously-returned page token representing part of the larger set of results to view. (String)

max

Maximum number of subscriptions to return. (Integer)

Returns

Array of Gcloud::Pubsub::Subscription (See Gcloud::Pubsub::Subscription::List)

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

subscriptions = pubsub.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

all_subs = []
tmp_subs = pubsub.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 = pubsub.subscriptions token: tmp_subs.token
end


533
534
535
536
537
538
539
540
541
542
# File 'lib/gcloud/pubsub/project.rb', line 533

def subscriptions prefix: nil, token: nil, max: nil
  ensure_connection!
  options = { prefix: prefix, token: token, max: max }
  resp = connection.list_subscriptions options
  if resp.success?
    Subscription::List.from_response resp, connection
  else
    fail ApiError.from_response(resp)
  end
end

#topic(topic_name, autocreate: nil, project: nil, skip_lookup: nil) ⇒ Object Also known as: get_topic, find_topic

Retrieves topic by name.

Parameters

topic_name

Name of a topic. (String)

autocreate

Flag to control whether the requested topic will be created if it does not exist. Ignored if skip_lookup is true. The default value is false. (Boolean)

project

If the topic belongs to a project other than the one currently connected to, the alternate project ID can be specified here. (String)

skip_lookup

Optionally create a Topic object without verifying the topic resource exists on the Pub/Sub service. Calls made on this object will raise errors if the topic resource does not exist. Default is false. (Boolean)

Returns

Gcloud::Pubsub::Topic or nil if topic does not exist. Will return a newly created Gcloud::Pubsub::Topic if the topic does not exist and autocreate is set to true.

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub
topic = pubsub.topic "existing-topic"

By default nil will be returned if the topic does not exist. the topic will be created in Pub/Sub when needed.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub
topic = pubsub.topic "non-existing-topic" #=> nil

The topic will be created if the topic does not exist and the autocreate option is set to true.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub
topic = pubsub.topic "non-existing-topic", autocreate: true

A topic in a different project can be created using the project flag.

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub
topic = pubsub.topic "another-topic", project: "another-project"

The lookup against the Pub/Sub service can be skipped using the skip_lookup option:

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub
topic = pubsub.topic "another-topic", skip_lookup: true


151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/gcloud/pubsub/project.rb', line 151

def topic topic_name, autocreate: nil, project: nil, skip_lookup: nil
  ensure_connection!
  options = { project: project }
  return Topic.new_lazy(topic_name, connection, options) if skip_lookup
  resp = connection.get_topic topic_name
  return Topic.from_gapi(resp.data, connection) if resp.success?
  if resp.status == 404
    return create_topic(topic_name) if autocreate
    return nil
  end
  fail ApiError.from_response(resp)
end

#topics(token: nil, max: nil) ⇒ Object Also known as: find_topics, list_topics

Retrieves a list of topics for the given project.

Parameters

token

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

max

Maximum number of topics to return. (Integer)

Returns

Array of Gcloud::Pubsub::Topic (See Gcloud::Pubsub::Topic::List)

Examples

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

topics = pubsub.topics
topics.each do |topic|
  puts topic.name
end

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

require "gcloud"

gcloud = Gcloud.new
pubsub = gcloud.pubsub

all_topics = []
tmp_topics = pubsub.topics
while tmp_topics.any? do
  tmp_topics.each do |topic|
    all_topics << topic
  end
  # break loop if no more topics available
  break if tmp_topics.token.nil?
  # get the next group of topics
  tmp_topics = pubsub.topics token: tmp_topics.token
end


245
246
247
248
249
250
251
252
253
254
# File 'lib/gcloud/pubsub/project.rb', line 245

def topics token: nil, max: nil
  ensure_connection!
  options = { token: token, max: max }
  resp = connection.list_topics options
  if resp.success?
    Topic::List.from_response resp, connection
  else
    fail ApiError.from_response(resp)
  end
end