google-cloud-node: pubsub.subscribe fails if called twice with the same subscription name

The sample code for pubsub will fail if it’s run twice.

The “subscribe” method:

topic.subscribe('new-subscription'...)

Will fail if “new-subscription” already exists. I see the following error:

Resource already exists in the project (resource=new-subscription).

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 29 (23 by maintainers)

Most upvoted comments

Maybe a simply solution for now is to just add { reuseExisting: true } to the README so users don’t get tripped up in their first 5 minutes

Hm - seems like that should be the default, no ?


Adding more context…

If we default to {reuseExisting: true}, we’re effectively saying “this is the worker model” in the sense that you’re creating more instances that will pull from the same subscription (ie, 1 message == 1 item of work)

If we default to {reuseExisting: false} (as we do today), we’re saying “this is the broadcast model” in that your each instance will get all the messages (ie, 1 message = N items, where N is the number of nodes).

For the worker model, names matter, and should be required. For the broadcast model, names don’t really matter so much (the topic matters a lot, but the name of the subscription doesn’t seem that useful, right?)

Is this ringing true with everyone? or am I crazy? @tmatsuo @stephenplusplus

You can use reuseExisting (https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.31.0/pubsub/topic?method=subscribe):

topic.subscribe('maybe-subscription-name', { reuseExisting: true }, function(err, subscription) {
  // subscription was "get-or-create"-ed
});

Another way to do it (this is a pattern throughout our whole API):

var subscription = topic.subscription('maybe-subscription-name');
subscription.get({ autoCreate: true }, function(err, subscription) {
  // subscription was "get-or-create"-ed
});