google-cloud-pubsub 2.22.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +27 -0
  3. data/OVERVIEW.md +188 -144
  4. data/lib/google/cloud/pubsub/admin_clients.rb +116 -0
  5. data/lib/google/cloud/pubsub/async_publisher.rb +9 -9
  6. data/lib/google/cloud/pubsub/batch_publisher.rb +4 -4
  7. data/lib/google/cloud/pubsub/errors.rb +3 -3
  8. data/lib/google/cloud/pubsub/message.rb +8 -8
  9. data/lib/google/cloud/pubsub/{subscriber → message_listener}/enumerator_queue.rb +1 -1
  10. data/lib/google/cloud/pubsub/{subscriber → message_listener}/inventory.rb +2 -4
  11. data/lib/google/cloud/pubsub/{subscriber → message_listener}/sequencer.rb +1 -1
  12. data/lib/google/cloud/pubsub/{subscriber → message_listener}/stream.rb +10 -10
  13. data/lib/google/cloud/pubsub/{subscriber → message_listener}/timed_unary_buffer.rb +1 -1
  14. data/lib/google/cloud/pubsub/message_listener.rb +413 -0
  15. data/lib/google/cloud/pubsub/project.rb +98 -531
  16. data/lib/google/cloud/pubsub/publisher.rb +373 -0
  17. data/lib/google/cloud/pubsub/received_message.rb +50 -45
  18. data/lib/google/cloud/pubsub/service.rb +24 -386
  19. data/lib/google/cloud/pubsub/subscriber.rb +442 -279
  20. data/lib/google/cloud/pubsub/version.rb +1 -1
  21. data/lib/google/cloud/pubsub.rb +8 -15
  22. data/lib/google-cloud-pubsub.rb +5 -4
  23. metadata +18 -26
  24. data/lib/google/cloud/pubsub/policy.rb +0 -188
  25. data/lib/google/cloud/pubsub/retry_policy.rb +0 -88
  26. data/lib/google/cloud/pubsub/schema/list.rb +0 -180
  27. data/lib/google/cloud/pubsub/schema.rb +0 -378
  28. data/lib/google/cloud/pubsub/snapshot/list.rb +0 -178
  29. data/lib/google/cloud/pubsub/snapshot.rb +0 -205
  30. data/lib/google/cloud/pubsub/subscription/list.rb +0 -205
  31. data/lib/google/cloud/pubsub/subscription/push_config.rb +0 -268
  32. data/lib/google/cloud/pubsub/subscription.rb +0 -1467
  33. data/lib/google/cloud/pubsub/topic/list.rb +0 -171
  34. data/lib/google/cloud/pubsub/topic.rb +0 -1100
@@ -1,1100 +0,0 @@
1
- # Copyright 2015 Google LLC
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # https://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
-
16
- require "google/cloud/errors"
17
- require "google/cloud/pubsub/topic/list"
18
- require "google/cloud/pubsub/async_publisher"
19
- require "google/cloud/pubsub/batch_publisher"
20
- require "google/cloud/pubsub/subscription"
21
- require "google/cloud/pubsub/policy"
22
- require "google/cloud/pubsub/retry_policy"
23
-
24
- module Google
25
- module Cloud
26
- module PubSub
27
- ##
28
- # # Topic
29
- #
30
- # A named resource to which messages are published.
31
- #
32
- # See {Project#create_topic} and {Project#topic}.
33
- #
34
- # @example
35
- # require "google/cloud/pubsub"
36
- #
37
- # pubsub = Google::Cloud::PubSub.new
38
- #
39
- # topic = pubsub.topic "my-topic"
40
- # topic.publish "task completed"
41
- #
42
- class Topic
43
- ##
44
- # @private The Service object.
45
- attr_accessor :service
46
-
47
- ##
48
- # @private The Google::Cloud::PubSub::V1::Topic object.
49
- attr_accessor :grpc
50
-
51
- ##
52
- # @private Create an empty {Topic} object.
53
- def initialize
54
- @service = nil
55
- @grpc = nil
56
- @resource_name = nil
57
- @exists = nil
58
- @async_opts = {}
59
- end
60
-
61
- ##
62
- # AsyncPublisher object used to publish multiple messages in batches.
63
- #
64
- # @return [AsyncPublisher] Returns publisher object if calls to
65
- # {#publish_async} have been made, returns `nil` otherwise.
66
- #
67
- # @example
68
- # require "google/cloud/pubsub"
69
- #
70
- # pubsub = Google::Cloud::PubSub.new
71
- #
72
- # topic = pubsub.topic "my-topic"
73
- # topic.publish_async "task completed" do |result|
74
- # if result.succeeded?
75
- # log_publish_success result.data
76
- # else
77
- # log_publish_failure result.data, result.error
78
- # end
79
- # end
80
- #
81
- # topic.async_publisher.stop!
82
- #
83
- def async_publisher
84
- @async_publisher
85
- end
86
-
87
- ##
88
- # The name of the topic.
89
- #
90
- # @return [String] A fully-qualified topic name in the form
91
- # `projects/{project_id}/topics/{topic_id}`.
92
- #
93
- def name
94
- return @resource_name if reference?
95
- @grpc.name
96
- end
97
-
98
- ##
99
- # A hash of user-provided labels associated with this topic. Labels can
100
- # be used to organize and group topics. See [Creating and Managing
101
- # Labels](https://cloud.google.com/pubsub/docs/labels).
102
- #
103
- # The returned hash is frozen and changes are not allowed. Use
104
- # {#labels=} to update the labels for this topic.
105
- #
106
- # Makes an API call to retrieve the labels values when called on a
107
- # reference object. See {#reference?}.
108
- #
109
- # @return [Hash] The frozen labels hash.
110
- #
111
- def labels
112
- ensure_grpc!
113
- @grpc.labels.to_h.freeze
114
- end
115
-
116
- ##
117
- # Sets the hash of user-provided labels associated with this
118
- # topic. Labels can be used to organize and group topics.
119
- # Label keys and values can be no longer than 63 characters, can only
120
- # contain lowercase letters, numeric characters, underscores and dashes.
121
- # International characters are allowed. Label values are optional. Label
122
- # keys must start with a letter and each label in the list must have a
123
- # different key. See [Creating and Managing
124
- # Labels](https://cloud.google.com/pubsub/docs/labels).
125
- #
126
- # @param [Hash] new_labels The new labels hash.
127
- #
128
- def labels= new_labels
129
- raise ArgumentError, "Value must be a Hash" if new_labels.nil?
130
- update_grpc = Google::Cloud::PubSub::V1::Topic.new name: name, labels: new_labels
131
- @grpc = service.update_topic update_grpc, :labels
132
- @resource_name = nil
133
- end
134
-
135
- ##
136
- # The Cloud KMS encryption key that will be used to protect access
137
- # to messages published on this topic.
138
- # For example: `projects/a/locations/b/keyRings/c/cryptoKeys/d`
139
- # The default value is `nil`, which means default encryption is used.
140
- #
141
- # Makes an API call to retrieve the KMS encryption key when called on a
142
- # reference object. See {#reference?}.
143
- #
144
- # @return [String]
145
- #
146
- # @example
147
- # require "google/cloud/pubsub"
148
- #
149
- # pubsub = Google::Cloud::PubSub.new
150
- #
151
- # topic = pubsub.topic "my-topic"
152
- #
153
- # topic.kms_key #=> "projects/a/locations/b/keyRings/c/cryptoKeys/d"
154
- #
155
- def kms_key
156
- ensure_grpc!
157
- @grpc.kms_key_name
158
- end
159
-
160
- ##
161
- # Set the Cloud KMS encryption key that will be used to protect access
162
- # to messages published on this topic.
163
- # For example: `projects/a/locations/b/keyRings/c/cryptoKeys/d`
164
- # The default value is `nil`, which means default encryption is used.
165
- #
166
- # @param [String] new_kms_key_name New Cloud KMS key name
167
- #
168
- # @example
169
- # require "google/cloud/pubsub"
170
- #
171
- # pubsub = Google::Cloud::PubSub.new
172
- #
173
- # topic = pubsub.topic "my-topic"
174
- #
175
- # key_name = "projects/a/locations/b/keyRings/c/cryptoKeys/d"
176
- # topic.kms_key = key_name
177
- #
178
- def kms_key= new_kms_key_name
179
- update_grpc = Google::Cloud::PubSub::V1::Topic.new name: name, kms_key_name: new_kms_key_name
180
- @grpc = service.update_topic update_grpc, :kms_key_name
181
- @resource_name = nil
182
- end
183
-
184
- ##
185
- # The list of GCP region IDs where messages that are published to the
186
- # topic may be persisted in storage.
187
- #
188
- # Messages published by publishers running in non-allowed GCP regions
189
- # (or running outside of GCP altogether) will be routed for storage in
190
- # one of the allowed regions. An empty list indicates a misconfiguration
191
- # at the project or organization level, which will result in all publish
192
- # operations failing.
193
- #
194
- # Makes an API call to retrieve the list of GCP region IDs values when
195
- # called on a reference object. See {#reference?}.
196
- #
197
- # @return [Array<String>]
198
- #
199
- # @example
200
- # require "google/cloud/pubsub"
201
- #
202
- # pubsub = Google::Cloud::PubSub.new
203
- #
204
- # topic = pubsub.topic "my-topic"
205
- #
206
- # topic.persistence_regions #=> ["us-central1", "us-central2"]
207
- #
208
- def persistence_regions
209
- ensure_grpc!
210
- return [] if @grpc.message_storage_policy.nil?
211
- Array @grpc.message_storage_policy.allowed_persistence_regions
212
- end
213
-
214
- ##
215
- # Sets the list of GCP region IDs where messages that are published to
216
- # the topic may be persisted in storage.
217
- #
218
- # @param [Array<String>] new_persistence_regions
219
- #
220
- # @example
221
- # require "google/cloud/pubsub"
222
- #
223
- # pubsub = Google::Cloud::PubSub.new
224
- #
225
- # topic = pubsub.topic "my-topic"
226
- #
227
- # topic.persistence_regions = ["us-central1", "us-central2"]
228
- #
229
- def persistence_regions= new_persistence_regions
230
- update_grpc = Google::Cloud::PubSub::V1::Topic.new \
231
- name: name, message_storage_policy: { allowed_persistence_regions: Array(new_persistence_regions) }
232
- @grpc = service.update_topic update_grpc, :message_storage_policy
233
- @resource_name = nil
234
- end
235
-
236
- ##
237
- # The name of the schema that messages published should be validated against, if schema settings are configured
238
- # for the topic. The value is a fully-qualified schema name in the form
239
- # `projects/{project_id}/schemas/{schema_id}`. If present, {#message_encoding} should also be present. The value
240
- # of this field will be `_deleted-schema_` if the schema has been deleted.
241
- #
242
- # Makes an API call to retrieve the schema settings when called on a reference object. See {#reference?}.
243
- #
244
- # @return [String, nil] The schema name, or `nil` if schema settings are not configured for the topic.
245
- #
246
- # @example
247
- # require "google/cloud/pubsub"
248
- #
249
- # pubsub = Google::Cloud::PubSub.new
250
- #
251
- # topic = pubsub.topic "my-topic"
252
- #
253
- # topic.schema_name #=> "projects/my-project/schemas/my-schema"
254
- #
255
- def schema_name
256
- ensure_grpc!
257
- @grpc.schema_settings&.schema
258
- end
259
-
260
- ##
261
- # The encoding of messages validated against the schema identified by {#schema_name}. If present, {#schema_name}
262
- # should also be present. Values include:
263
- #
264
- # * `JSON` - JSON encoding.
265
- # * `BINARY` - Binary encoding, as defined by the schema type. For some schema types, binary encoding may not be
266
- # available.
267
- #
268
- # Makes an API call to retrieve the schema settings when called on a reference object. See {#reference?}.
269
- #
270
- # @return [Symbol, nil] The schema encoding, or `nil` if schema settings are not configured for the topic.
271
- #
272
- # @example
273
- # require "google/cloud/pubsub"
274
- #
275
- # pubsub = Google::Cloud::PubSub.new
276
- #
277
- # topic = pubsub.topic "my-topic"
278
- #
279
- # topic.message_encoding #=> :JSON
280
- #
281
- def message_encoding
282
- ensure_grpc!
283
- @grpc.schema_settings&.encoding
284
- end
285
-
286
- ##
287
- # Checks if the encoding of messages in the schema settings is `BINARY`. See {#message_encoding}.
288
- #
289
- # Makes an API call to retrieve the schema settings when called on a reference object. See {#reference?}.
290
- #
291
- # @return [Boolean] `true` when `BINARY`, `false` if not `BINARY` or schema settings is not set.
292
- #
293
- def message_encoding_binary?
294
- message_encoding.to_s.upcase == "BINARY"
295
- end
296
-
297
- ##
298
- # Checks if the encoding of messages in the schema settings is `JSON`. See {#message_encoding}.
299
- #
300
- # Makes an API call to retrieve the schema settings when called on a reference object. See {#reference?}.
301
- #
302
- # @return [Boolean] `true` when `JSON`, `false` if not `JSON` or schema settings is not set.
303
- #
304
- def message_encoding_json?
305
- message_encoding.to_s.upcase == "JSON"
306
- end
307
-
308
- ##
309
- # Indicates the minimum number of seconds to retain a message after it is
310
- # published to the topic. If this field is set, messages published to the topic
311
- # within the `retention` number of seconds are always available to subscribers.
312
- # For instance, it allows any attached subscription to [seek to a
313
- # timestamp](https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time)
314
- # that is up to `retention` number of seconds in the past. If this field is
315
- # not set, message retention is controlled by settings on individual
316
- # subscriptions. Cannot be less than 600 (10 minutes) or more than 604,800 (7 days).
317
- # See {#retention=}.
318
- #
319
- # Makes an API call to retrieve the retention value when called on a
320
- # reference object. See {#reference?}.
321
- #
322
- # @return [Numeric, nil] The message retention duration in seconds, or `nil` if not set.
323
- #
324
- def retention
325
- ensure_grpc!
326
- Convert.duration_to_number @grpc.message_retention_duration
327
- end
328
-
329
- ##
330
- # Sets the message retention duration in seconds. If set to a positive duration
331
- # between 600 (10 minutes) and 604,800 (7 days), inclusive, the message retention
332
- # duration is changed. If set to `nil`, this clears message retention duration
333
- # from the topic. See {#retention}.
334
- #
335
- # @param [Numeric, nil] new_retention The new message retention duration value.
336
- #
337
- def retention= new_retention
338
- new_retention_duration = Convert.number_to_duration new_retention
339
- update_grpc = Google::Cloud::PubSub::V1::Topic.new name: name,
340
- message_retention_duration: new_retention_duration
341
- @grpc = service.update_topic update_grpc, :message_retention_duration
342
- @resource_name = nil
343
- end
344
-
345
- ##
346
- # Permanently deletes the topic.
347
- #
348
- # @return [Boolean] Returns `true` if the topic was deleted.
349
- #
350
- # @example
351
- # require "google/cloud/pubsub"
352
- #
353
- # pubsub = Google::Cloud::PubSub.new
354
- #
355
- # topic = pubsub.topic "my-topic"
356
- # topic.delete
357
- #
358
- def delete
359
- ensure_service!
360
- service.delete_topic name
361
- true
362
- end
363
-
364
- ##
365
- # Creates a new {Subscription} object on the current Topic.
366
- #
367
- # @option options [String] subscription_name Name of the new subscription. Required.
368
- # The value can be a simple subscription ID (relative name), in which
369
- # case the current project ID will be supplied, or a fully-qualified
370
- # subscription name in the form
371
- # `projects/{project_id}/subscriptions/{subscription_id}`.
372
- #
373
- # The subscription ID (relative name) must start with a letter, and
374
- # contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`),
375
- # underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent
376
- # signs (`%`). It must be between 3 and 255 characters in length, and
377
- # it must not start with `goog`.
378
- # @option options [Integer] deadline The maximum number of seconds after a
379
- # subscriber receives a message before the subscriber should
380
- # acknowledge the message.
381
- # @option options [Boolean] retain_acked Indicates whether to retain acknowledged
382
- # messages. If `true`, then messages are not expunged from the
383
- # subscription's backlog, even if they are acknowledged, until they
384
- # fall out of the `retention` window. Default is `false`.
385
- # @option options [Numeric] retention How long to retain unacknowledged messages
386
- # in the subscription's backlog, from the moment a message is
387
- # published. If `retain_acked` is `true`, then this also configures
388
- # the retention of acknowledged messages, and thus configures how far
389
- # back in time a {Subscription#seek} can be done. Cannot be more than
390
- # 604,800 seconds (7 days) or less than 600 seconds (10 minutes).
391
- # Default is 604,800 seconds (7 days).
392
- # @option options [String] endpoint A URL locating the endpoint to which messages
393
- # should be pushed. The parameters `push_config` and `endpoint` should not both be provided.
394
- # @option options [Google::Cloud::PubSub::Subscription::PushConfig] push_config
395
- # The configuration for a push delivery endpoint that should contain the endpoint,
396
- # and can contain authentication data (OIDC token authentication).
397
- # The parameters `push_config` and `endpoint` should not both be provided.
398
- # @option options [Hash] labels A hash of user-provided labels associated with
399
- # the subscription. You can use these to organize and group your
400
- # subscriptions. Label keys and values can be no longer than 63
401
- # characters, can only contain lowercase letters, numeric characters,
402
- # underscores and dashes. International characters are allowed. Label
403
- # values are optional. Label keys must start with a letter and each
404
- # label in the list must have a different key. See [Creating and
405
- # Managing Labels](https://cloud.google.com/pubsub/docs/labels).
406
- # @option options [Boolean] message_ordering Whether to enable message ordering
407
- # on the subscription.
408
- # @option options [String] filter An expression written in the Cloud Pub/Sub filter language.
409
- # If non-empty, then only {Message} instances whose `attributes` field
410
- # matches the filter are delivered on this subscription. If
411
- # empty, then no messages are filtered out. Optional.
412
- # @option options [Topic] dead_letter_topic
413
- # The {Topic} to which dead letter messages for the subscription should be published.
414
- # Dead lettering is done on a best effort basis. The same message might be dead lettered multiple
415
- # times. The Cloud Pub/Sub service account associated with the enclosing subscription's parent project (i.e.,
416
- # `service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com`) must have permission to Publish() to
417
- # this topic.
418
- #
419
- # The operation will fail if the topic does not exist. Users should ensure that there is a subscription
420
- # attached to this topic since messages published to a topic with no subscriptions are lost.
421
- # @option options [Integer] dead_letter_max_delivery_attempts
422
- # The maximum number of delivery attempts for any message in the subscription's dead letter policy.
423
- # Dead lettering is done on a best effort basis. The same message might
424
- # be dead lettered multiple times. The value must be between 5 and 100. If this parameter is 0, a default
425
- # value of 5 is used. The `dead_letter_topic` must also be set.
426
- # @option options [RetryPolicy] retry_policy
427
- # A policy that specifies how Cloud Pub/Sub retries message delivery for this subscription.
428
- # If not set, the default retry policy is applied. This generally implies that messages
429
- # will be retried as soon as possible for healthy subscribers. Retry Policy will be triggered on NACKs or
430
- # acknowledgement deadline exceeded events for a given message.
431
- #
432
- # @return [Google::Cloud::PubSub::Subscription]
433
- #
434
- # @example
435
- # require "google/cloud/pubsub"
436
- #
437
- # pubsub = Google::Cloud::PubSub.new
438
- #
439
- # topic = pubsub.topic "my-topic"
440
- # sub = topic.subscribe "my-topic-sub"
441
- # sub.name # => "my-topic-sub"
442
- #
443
- # @example Wait 2 minutes for acknowledgement:
444
- # require "google/cloud/pubsub"
445
- #
446
- # pubsub = Google::Cloud::PubSub.new
447
- #
448
- # topic = pubsub.topic "my-topic"
449
- # sub = topic.subscribe "my-topic-sub",
450
- # deadline: 120
451
- #
452
- # @example Configure a push endpoint:
453
- # require "google/cloud/pubsub"
454
- #
455
- # pubsub = Google::Cloud::PubSub.new
456
- # topic = pubsub.topic "my-topic"
457
- #
458
- # push_config = Google::Cloud::PubSub::Subscription::PushConfig.new endpoint: "http://example.net/callback"
459
- # push_config.set_oidc_token "service-account@example.net", "audience-header-value"
460
- #
461
- # sub = topic.subscribe "my-subscription", push_config: push_config
462
- #
463
- # @example Configure a Dead Letter Queues policy:
464
- # require "google/cloud/pubsub"
465
- #
466
- # pubsub = Google::Cloud::PubSub.new
467
- #
468
- # # Dead Letter Queue (DLQ) testing requires IAM bindings to the Cloud Pub/Sub service account that is
469
- # # automatically created and managed by the service team in a private project.
470
- # my_project_number = "000000000000"
471
- # service_account_email = "serviceAccount:service-#{my_project_number}@gcp-sa-pubsub.iam.gserviceaccount.com"
472
- #
473
- # dead_letter_topic = pubsub.topic "my-dead-letter-topic"
474
- # dead_letter_subscription = dead_letter_topic.subscribe "my-dead-letter-sub"
475
- #
476
- # dead_letter_topic.policy { |p| p.add "roles/pubsub.publisher", service_account_email }
477
- # dead_letter_subscription.policy { |p| p.add "roles/pubsub.subscriber", service_account_email }
478
- #
479
- # topic = pubsub.topic "my-topic"
480
- # sub = topic.subscribe "my-topic-sub",
481
- # dead_letter_topic: dead_letter_topic,
482
- # dead_letter_max_delivery_attempts: 10
483
- #
484
- # @example Configure a Retry Policy:
485
- # require "google/cloud/pubsub"
486
- #
487
- # pubsub = Google::Cloud::PubSub.new
488
- #
489
- # topic = pubsub.topic "my-topic"
490
- #
491
- # retry_policy = Google::Cloud::PubSub::RetryPolicy.new minimum_backoff: 5, maximum_backoff: 300
492
- # sub = topic.subscribe "my-topic-sub", retry_policy: retry_policy
493
- #
494
- def subscribe subscription_name, **options
495
- ensure_service!
496
- if options[:push_config] && options[:endpoint]
497
- raise ArgumentError, "endpoint and push_config were both provided. Please provide only one."
498
- end
499
- if options[:endpoint]
500
- options[:push_config] =
501
- Google::Cloud::PubSub::Subscription::PushConfig.new endpoint: options[:endpoint]
502
- end
503
-
504
- options[:dead_letter_topic_name] = options[:dead_letter_topic].name if options[:dead_letter_topic]
505
- if options[:dead_letter_max_delivery_attempts] && !options[:dead_letter_topic_name]
506
- # Service error message "3:Invalid resource name given (name=)." does not identify param.
507
- raise ArgumentError, "dead_letter_topic is required with dead_letter_max_delivery_attempts"
508
- end
509
- options[:push_config] = options[:push_config].to_grpc if options[:push_config]
510
- options[:retry_policy] = options[:retry_policy].to_grpc if options[:retry_policy]
511
- grpc = service.create_subscription name, subscription_name, options
512
- Subscription.from_grpc grpc, service
513
- end
514
- alias create_subscription subscribe
515
- alias new_subscription subscribe
516
-
517
- ##
518
- # Retrieves subscription by name.
519
- #
520
- # @param [String] subscription_name Name of a subscription. The value
521
- # can be a simple subscription ID (relative name), in which case the
522
- # current project ID will be supplied, or a fully-qualified
523
- # subscription name in the form
524
- # `projects/{project_id}/subscriptions/{subscription_id}`.
525
- # @param [Boolean] skip_lookup Optionally create a {Subscription} object
526
- # without verifying the subscription resource exists on the Pub/Sub
527
- # service. Calls made on this object will raise errors if the service
528
- # resource does not exist. Default is `false`.
529
- #
530
- # @return [Google::Cloud::PubSub::Subscription, nil] Returns `nil` if
531
- # the subscription does not exist.
532
- #
533
- # @example
534
- # require "google/cloud/pubsub"
535
- #
536
- # pubsub = Google::Cloud::PubSub.new
537
- #
538
- # topic = pubsub.topic "my-topic"
539
- #
540
- # sub = topic.subscription "my-topic-sub"
541
- # sub.name #=> "projects/my-project/subscriptions/my-topic-sub"
542
- #
543
- # @example Skip the lookup against the service with `skip_lookup`:
544
- # require "google/cloud/pubsub"
545
- #
546
- # pubsub = Google::Cloud::PubSub.new
547
- #
548
- # topic = pubsub.topic "my-topic"
549
- #
550
- # # No API call is made to retrieve the subscription information.
551
- # sub = topic.subscription "my-topic-sub", skip_lookup: true
552
- # sub.name #=> "projects/my-project/subscriptions/my-topic-sub"
553
- #
554
- def subscription subscription_name, skip_lookup: nil
555
- ensure_service!
556
- return Subscription.from_name subscription_name, service if skip_lookup
557
- grpc = service.get_subscription subscription_name
558
- Subscription.from_grpc grpc, service
559
- rescue Google::Cloud::NotFoundError
560
- nil
561
- end
562
- alias get_subscription subscription
563
- alias find_subscription subscription
564
-
565
- ##
566
- # Retrieves a list of subscription names for the given project.
567
- #
568
- # @param [String] token The `token` value returned by the last call to
569
- # `subscriptions`; indicates that this is a continuation of a call,
570
- # and that the system should return the next page of data.
571
- # @param [Integer] max Maximum number of subscriptions to return.
572
- #
573
- # @return [Array<Subscription>] (See {Subscription::List})
574
- #
575
- # @example
576
- # require "google/cloud/pubsub"
577
- #
578
- # pubsub = Google::Cloud::PubSub.new
579
- #
580
- # topic = pubsub.topic "my-topic"
581
- # subscriptions = topic.subscriptions
582
- # subscriptions.each do |subscription|
583
- # puts subscription.name
584
- # end
585
- #
586
- # @example Retrieve all subscriptions: (See {Subscription::List#all})
587
- # require "google/cloud/pubsub"
588
- #
589
- # pubsub = Google::Cloud::PubSub.new
590
- #
591
- # topic = pubsub.topic "my-topic"
592
- # subscriptions = topic.subscriptions
593
- # subscriptions.all do |subscription|
594
- # puts subscription.name
595
- # end
596
- #
597
- def subscriptions token: nil, max: nil
598
- ensure_service!
599
- options = { token: token, max: max }
600
- grpc = service.list_topics_subscriptions name, options
601
- Subscription::List.from_topic_grpc grpc, service, name, max
602
- end
603
- alias find_subscriptions subscriptions
604
- alias list_subscriptions subscriptions
605
-
606
- ##
607
- # Publishes one or more messages to the topic.
608
- #
609
- # The message payload must not be empty; it must contain either a
610
- # non-empty data field, or at least one attribute.
611
- #
612
- # @param [String, File] data The message payload. This will be converted
613
- # to bytes encoded as ASCII-8BIT.
614
- # @param [Hash] attributes Optional attributes for the message.
615
- # @param [String] ordering_key Identifies related messages for which
616
- # publish order should be respected.
617
- # @yield [batch] a block for publishing multiple messages in one
618
- # request
619
- # @yieldparam [BatchPublisher] batch the topic batch publisher
620
- # object
621
- #
622
- # @return [Message, Array<Message>] Returns the published message when
623
- # called without a block, or an array of messages when called with a
624
- # block.
625
- #
626
- # @example
627
- # require "google/cloud/pubsub"
628
- #
629
- # pubsub = Google::Cloud::PubSub.new
630
- #
631
- # topic = pubsub.topic "my-topic"
632
- # msg = topic.publish "task completed"
633
- #
634
- # @example A message can be published using a File object:
635
- # require "google/cloud/pubsub"
636
- #
637
- # pubsub = Google::Cloud::PubSub.new
638
- #
639
- # topic = pubsub.topic "my-topic"
640
- # file = File.open "message.txt", mode: "rb"
641
- # msg = topic.publish file
642
- #
643
- # @example Additionally, a message can be published with attributes:
644
- # require "google/cloud/pubsub"
645
- #
646
- # pubsub = Google::Cloud::PubSub.new
647
- #
648
- # topic = pubsub.topic "my-topic"
649
- # msg = topic.publish "task completed",
650
- # foo: :bar,
651
- # this: :that
652
- #
653
- # @example Multiple messages can be sent at the same time using a block:
654
- # require "google/cloud/pubsub"
655
- #
656
- # pubsub = Google::Cloud::PubSub.new
657
- #
658
- # topic = pubsub.topic "my-topic"
659
- # msgs = topic.publish do |t|
660
- # t.publish "task 1 completed", foo: :bar
661
- # t.publish "task 2 completed", foo: :baz
662
- # t.publish "task 3 completed", foo: :bif
663
- # end
664
- #
665
- # @example Ordered messages are supported using ordering_key:
666
- # require "google/cloud/pubsub"
667
- #
668
- # pubsub = Google::Cloud::PubSub.new
669
- #
670
- # topic = pubsub.topic "my-ordered-topic"
671
- #
672
- # # Ensure that message ordering is enabled.
673
- # topic.enable_message_ordering!
674
- #
675
- # # Publish an ordered message with an ordering key.
676
- # topic.publish "task completed",
677
- # ordering_key: "task-key"
678
- #
679
- def publish data = nil, attributes = nil, ordering_key: nil, compress: nil, compression_bytes_threshold: nil,
680
- **extra_attrs, &block
681
- ensure_service!
682
- batch = BatchPublisher.new data,
683
- attributes,
684
- ordering_key,
685
- extra_attrs,
686
- compress: compress,
687
- compression_bytes_threshold: compression_bytes_threshold
688
-
689
- block&.call batch
690
- return nil if batch.messages.count.zero?
691
- batch.publish_batch_messages name, service
692
- end
693
-
694
- ##
695
- # Publishes a message asynchronously to the topic using
696
- # {#async_publisher}.
697
- #
698
- # The message payload must not be empty; it must contain either a
699
- # non-empty data field, or at least one attribute.
700
- #
701
- # Google Cloud Pub/Sub ordering keys provide the ability to ensure
702
- # related messages are sent to subscribers in the order in which they
703
- # were published. Messages can be tagged with an ordering key, a string
704
- # that identifies related messages for which publish order should be
705
- # respected. The service guarantees that, for a given ordering key and
706
- # publisher, messages are sent to subscribers in the order in which they
707
- # were published. Ordering does not require sacrificing high throughput
708
- # or scalability, as the service automatically distributes messages for
709
- # different ordering keys across subscribers.
710
- #
711
- # To use ordering keys, specify `ordering_key`. Before specifying
712
- # `ordering_key` on a message a call to `#enable_message_ordering!` must
713
- # be made or an error will be raised.
714
- #
715
- # @note At the time of this release, ordering keys are not yet publicly
716
- # enabled and requires special project enablements.
717
- #
718
- # Publisher flow control limits the number of outstanding messages that
719
- # are allowed to wait to be published. See the `flow_control` key in the
720
- # `async` parameter in {Project#topic} for more information about publisher
721
- # flow control settings.
722
- #
723
- # @param [String, File] data The message payload. This will be converted
724
- # to bytes encoded as ASCII-8BIT.
725
- # @param [Hash] attributes Optional attributes for the message.
726
- # @param [String] ordering_key Identifies related messages for which
727
- # publish order should be respected.
728
- # @yield [result] the callback for when the message has been published
729
- # @yieldparam [PublishResult] result the result of the asynchronous
730
- # publish
731
- # @raise [Google::Cloud::PubSub::AsyncPublisherStopped] when the
732
- # publisher is stopped. (See {AsyncPublisher#stop} and
733
- # {AsyncPublisher#stopped?}.)
734
- # @raise [Google::Cloud::PubSub::OrderedMessagesDisabled] when
735
- # publishing a message with an `ordering_key` but ordered messages are
736
- # not enabled. (See {#message_ordering?} and
737
- # {#enable_message_ordering!}.)
738
- # @raise [Google::Cloud::PubSub::OrderingKeyError] when publishing a
739
- # message with an `ordering_key` that has already failed when
740
- # publishing. Use {#resume_publish} to allow this `ordering_key` to be
741
- # published again.
742
- # @raise [Google::Cloud::PubSub::FlowControlLimitError] when publish flow
743
- # control limits are exceeded, and the `async` parameter key
744
- # `flow_control.limit_exceeded_behavior` is set to `:error` or `:block`.
745
- # If `flow_control.limit_exceeded_behavior` is set to `:block`, this error
746
- # will be raised only when a limit would be exceeded by a single message.
747
- # See the `async` parameter in {Project#topic} for more information about
748
- # `flow_control` settings.
749
- #
750
- # @example
751
- # require "google/cloud/pubsub"
752
- #
753
- # pubsub = Google::Cloud::PubSub.new
754
- #
755
- # topic = pubsub.topic "my-topic"
756
- # topic.publish_async "task completed" do |result|
757
- # if result.succeeded?
758
- # log_publish_success result.data
759
- # else
760
- # log_publish_failure result.data, result.error
761
- # end
762
- # end
763
- #
764
- # # Shut down the publisher when ready to stop publishing messages.
765
- # topic.async_publisher.stop!
766
- #
767
- # @example A message can be published using a File object:
768
- # require "google/cloud/pubsub"
769
- #
770
- # pubsub = Google::Cloud::PubSub.new
771
- #
772
- # topic = pubsub.topic "my-topic"
773
- # file = File.open "message.txt", mode: "rb"
774
- # topic.publish_async file
775
- #
776
- # # Shut down the publisher when ready to stop publishing messages.
777
- # topic.async_publisher.stop!
778
- #
779
- # @example Additionally, a message can be published with attributes:
780
- # require "google/cloud/pubsub"
781
- #
782
- # pubsub = Google::Cloud::PubSub.new
783
- #
784
- # topic = pubsub.topic "my-topic"
785
- # topic.publish_async "task completed",
786
- # foo: :bar, this: :that
787
- #
788
- # # Shut down the publisher when ready to stop publishing messages.
789
- # topic.async_publisher.stop!
790
- #
791
- # @example Ordered messages are supported using ordering_key:
792
- # require "google/cloud/pubsub"
793
- #
794
- # pubsub = Google::Cloud::PubSub.new
795
- #
796
- # topic = pubsub.topic "my-ordered-topic"
797
- #
798
- # # Ensure that message ordering is enabled.
799
- # topic.enable_message_ordering!
800
- #
801
- # # Publish an ordered message with an ordering key.
802
- # topic.publish_async "task completed",
803
- # ordering_key: "task-key"
804
- #
805
- # # Shut down the publisher when ready to stop publishing messages.
806
- # topic.async_publisher.stop!
807
- #
808
- def publish_async data = nil, attributes = nil, ordering_key: nil, **extra_attrs, &callback
809
- ensure_service!
810
-
811
- @async_publisher ||= AsyncPublisher.new name, service, **@async_opts
812
- @async_publisher.publish data, attributes, ordering_key: ordering_key, **extra_attrs, &callback
813
- end
814
-
815
- ##
816
- # Enables message ordering for messages with ordering keys on the
817
- # {#async_publisher}. When enabled, messages published with the same
818
- # `ordering_key` will be delivered in the order they were published.
819
- #
820
- # @note At the time of this release, ordering keys are not yet publicly
821
- # enabled and requires special project enablements.
822
- #
823
- # See {#message_ordering?}. See {#publish_async},
824
- # {Subscription#listen}, and {Message#ordering_key}.
825
- #
826
- def enable_message_ordering!
827
- @async_publisher ||= AsyncPublisher.new name, service, **@async_opts
828
- @async_publisher.enable_message_ordering!
829
- end
830
-
831
- ##
832
- # Whether message ordering for messages with ordering keys has been
833
- # enabled on the {#async_publisher}. When enabled, messages published
834
- # with the same `ordering_key` will be delivered in the order they were
835
- # published. When disabled, messages may be delivered in any order.
836
- #
837
- # See {#enable_message_ordering!}. See {#publish_async},
838
- # {Subscription#listen}, and {Message#ordering_key}.
839
- #
840
- # @return [Boolean]
841
- #
842
- def message_ordering?
843
- @async_publisher ||= AsyncPublisher.new name, service, **@async_opts
844
- @async_publisher.message_ordering?
845
- end
846
-
847
- ##
848
- # Resume publishing ordered messages for the provided ordering key.
849
- #
850
- # @param [String] ordering_key Identifies related messages for which
851
- # publish order should be respected.
852
- #
853
- # @return [boolean] `true` when resumed, `false` otherwise.
854
- #
855
- def resume_publish ordering_key
856
- @async_publisher ||= AsyncPublisher.new name, service, **@async_opts
857
- @async_publisher.resume_publish ordering_key
858
- end
859
-
860
- ##
861
- # Gets the [Cloud IAM](https://cloud.google.com/iam/) access control
862
- # policy for this topic.
863
- #
864
- # @see https://cloud.google.com/pubsub/docs/reference/rpc/google.iam.v1#iampolicy
865
- # google.iam.v1.IAMPolicy
866
- #
867
- # @yield [policy] A block for updating the policy. The latest policy
868
- # will be read from the Pub/Sub service and passed to the block. After
869
- # the block completes, the modified policy will be written to the
870
- # service.
871
- # @yieldparam [Policy] policy the current Cloud IAM Policy for this
872
- # topic
873
- #
874
- # @return [Policy] the current Cloud IAM Policy for this topic
875
- #
876
- # @example
877
- # require "google/cloud/pubsub"
878
- #
879
- # pubsub = Google::Cloud::PubSub.new
880
- # topic = pubsub.topic "my-topic"
881
- #
882
- # policy = topic.policy
883
- #
884
- # @example Update the policy by passing a block:
885
- # require "google/cloud/pubsub"
886
- #
887
- # pubsub = Google::Cloud::PubSub.new
888
- # topic = pubsub.topic "my-topic"
889
- #
890
- # topic.policy do |p|
891
- # p.add "roles/owner", "user:owner@example.com"
892
- # end
893
- #
894
- def policy
895
- ensure_service!
896
- grpc = service.get_topic_policy name
897
- policy = Policy.from_grpc grpc
898
- return policy unless block_given?
899
- yield policy
900
- update_policy policy
901
- end
902
-
903
- ##
904
- # Updates the [Cloud IAM](https://cloud.google.com/iam/) access control
905
- # policy for this topic. The policy should be read from {#policy}. See
906
- # {Google::Cloud::PubSub::Policy} for an explanation of the policy
907
- # `etag` property and how to modify policies.
908
- #
909
- # You can also update the policy by passing a block to {#policy}, which
910
- # will call this method internally after the block completes.
911
- #
912
- # @see https://cloud.google.com/pubsub/docs/reference/rpc/google.iam.v1#iampolicy
913
- # google.iam.v1.IAMPolicy
914
- #
915
- # @param [Policy] new_policy a new or modified Cloud IAM Policy for this
916
- # topic
917
- #
918
- # @return [Policy] the policy returned by the API update operation
919
- #
920
- # @example
921
- # require "google/cloud/pubsub"
922
- #
923
- # pubsub = Google::Cloud::PubSub.new
924
- # topic = pubsub.topic "my-topic"
925
- #
926
- # policy = topic.policy # API call
927
- #
928
- # policy.add "roles/owner", "user:owner@example.com"
929
- #
930
- # topic.update_policy policy # API call
931
- #
932
- def update_policy new_policy
933
- ensure_service!
934
- grpc = service.set_topic_policy name, new_policy.to_grpc
935
- @policy = Policy.from_grpc grpc
936
- end
937
- alias policy= update_policy
938
-
939
- ##
940
- # Tests the specified permissions against the [Cloud
941
- # IAM](https://cloud.google.com/iam/) access control policy.
942
- #
943
- # @see https://cloud.google.com/iam/docs/managing-policies Managing
944
- # Policies
945
- #
946
- # @param [String, Array<String>] permissions The set of permissions to
947
- # check access for. Permissions with wildcards (such as `*` or
948
- # `storage.*`) are not allowed.
949
- #
950
- # The permissions that can be checked on a topic are:
951
- #
952
- # * pubsub.topics.publish
953
- # * pubsub.topics.attachSubscription
954
- # * pubsub.topics.get
955
- # * pubsub.topics.delete
956
- # * pubsub.topics.update
957
- # * pubsub.topics.getIamPolicy
958
- # * pubsub.topics.setIamPolicy
959
- #
960
- # @return [Array<Strings>] The permissions that have access.
961
- #
962
- # @example
963
- # require "google/cloud/pubsub"
964
- #
965
- # pubsub = Google::Cloud::PubSub.new
966
- # topic = pubsub.topic "my-topic"
967
- # perms = topic.test_permissions "pubsub.topics.get",
968
- # "pubsub.topics.publish"
969
- # perms.include? "pubsub.topics.get" #=> true
970
- # perms.include? "pubsub.topics.publish" #=> false
971
- #
972
- def test_permissions *permissions
973
- permissions = Array(permissions).flatten
974
- permissions = Array(permissions).flatten
975
- ensure_service!
976
- grpc = service.test_topic_permissions name, permissions
977
- grpc.permissions
978
- end
979
-
980
- ##
981
- # Determines whether the topic exists in the Pub/Sub service.
982
- #
983
- # @example
984
- # require "google/cloud/pubsub"
985
- #
986
- # pubsub = Google::Cloud::PubSub.new
987
- #
988
- # topic = pubsub.topic "my-topic"
989
- # topic.exists? #=> true
990
- #
991
- def exists?
992
- # Always true if the object is not set as reference
993
- return true unless reference?
994
- # If we have a value, return it
995
- return @exists unless @exists.nil?
996
- ensure_grpc!
997
- @exists = true
998
- rescue Google::Cloud::NotFoundError
999
- @exists = false
1000
- end
1001
-
1002
- ##
1003
- # Determines whether the topic object was created without retrieving the
1004
- # resource representation from the Pub/Sub service.
1005
- #
1006
- # @return [Boolean] `true` when the topic was created without a resource
1007
- # representation, `false` otherwise.
1008
- #
1009
- # @example
1010
- # require "google/cloud/pubsub"
1011
- #
1012
- # pubsub = Google::Cloud::PubSub.new
1013
- #
1014
- # topic = pubsub.topic "my-topic", skip_lookup: true
1015
- # topic.reference? #=> true
1016
- #
1017
- def reference?
1018
- @grpc.nil?
1019
- end
1020
-
1021
- ##
1022
- # Determines whether the topic object was created with a resource
1023
- # representation from the Pub/Sub service.
1024
- #
1025
- # @return [Boolean] `true` when the topic was created with a resource
1026
- # representation, `false` otherwise.
1027
- #
1028
- # @example
1029
- # require "google/cloud/pubsub"
1030
- #
1031
- # pubsub = Google::Cloud::PubSub.new
1032
- #
1033
- # topic = pubsub.topic "my-topic"
1034
- # topic.resource? #=> true
1035
- #
1036
- def resource?
1037
- !@grpc.nil?
1038
- end
1039
-
1040
- ##
1041
- # Reloads the topic with current data from the Pub/Sub service.
1042
- #
1043
- # @return [Google::Cloud::PubSub::Topic] Returns the reloaded topic
1044
- #
1045
- # @example
1046
- # require "google/cloud/pubsub"
1047
- #
1048
- # pubsub = Google::Cloud::PubSub.new
1049
- #
1050
- # topic = pubsub.topic "my-topic"
1051
- # topic.reload!
1052
- #
1053
- def reload!
1054
- ensure_service!
1055
- @grpc = service.get_topic name
1056
- @resource_name = nil
1057
- self
1058
- end
1059
- alias refresh! reload!
1060
-
1061
- ##
1062
- # @private New Topic from a Google::Cloud::PubSub::V1::Topic object.
1063
- def self.from_grpc grpc, service, async: nil
1064
- new.tap do |t|
1065
- t.grpc = grpc
1066
- t.service = service
1067
- t.instance_variable_set :@async_opts, async if async
1068
- end
1069
- end
1070
-
1071
- ##
1072
- # @private New reference {Topic} object without making an HTTP request.
1073
- def self.from_name name, service, options = {}
1074
- name = service.topic_path name, options
1075
- from_grpc(nil, service, async: options[:async]).tap do |t|
1076
- t.instance_variable_set :@resource_name, name
1077
- end
1078
- end
1079
-
1080
- protected
1081
-
1082
- ##
1083
- # @private Raise an error unless an active connection to the service is
1084
- # available.
1085
- def ensure_service!
1086
- raise "Must have active connection to service" unless service
1087
- end
1088
-
1089
- ##
1090
- # Ensures a Google::Cloud::PubSub::V1::Topic object exists.
1091
- def ensure_grpc!
1092
- ensure_service!
1093
- reload! if reference?
1094
- end
1095
- end
1096
- end
1097
-
1098
- Pubsub = PubSub unless const_defined? :Pubsub
1099
- end
1100
- end