diff --git a/README.md b/README.md index 330e594c74..fdbf1292f7 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,7 @@ allows you to send and receive messages between independent applications. View the [Cloud Pub/Sub Node.js samples][pubsub_samples]. [pubsub_docs]: https://cloud.google.com/pubsub/docs/ -[pubsub_samples]: pubsub +[pubsub_samples]: https://github.com/googleapis/nodejs-pubsub/tree/master/samples ### Machine Learning diff --git a/circle.yml b/circle.yml index c6839c0609..0b1266544a 100644 --- a/circle.yml +++ b/circle.yml @@ -110,6 +110,5 @@ deployment: - node scripts/build "kms" - node scripts/build "language/slackbot" - node scripts/build "prediction" - - node scripts/build "pubsub" - node scripts/build "storage-transfer" - node scripts/build "trace" diff --git a/pubsub/README.md b/pubsub/README.md index 7f52f194bf..84d7cd68e7 100644 --- a/pubsub/README.md +++ b/pubsub/README.md @@ -1,141 +1,5 @@ -Google Cloud Platform logo +Samples for the [PubSub API Node.js Client][client] have moved to +[github.com/googleapis/nodejs-pubsub/tree/master/samples/][samples]. -# Google Cloud Pub/Sub Node.js Samples - -[![Build](https://storage.googleapis.com/cloud-docs-samples-badges/GoogleCloudPlatform/nodejs-docs-samples/nodejs-docs-samples-pubsub.svg)]() - -[Cloud Pub/Sub](https://cloud.google.com/pubsub/docs) is a fully-managed real-time messaging service that allows you to send and receive messages between independent applications. - -## Table of Contents - -* [Setup](#setup) -* [Samples](#samples) - * [Topics](#topics) - * [Subscriptions](#subscriptions) -* [Running the tests](#running-the-tests) - -## Setup - -1. Read [Prerequisites][prereq] and [How to run a sample][run] first. -1. Install dependencies: - - With **npm**: - - npm install - - With **yarn**: - - yarn install - -[prereq]: ../README.md#prerequisites -[run]: ../README.md#how-to-run-a-sample - -## Samples - -### Topics - -View the [documentation][topics_0_docs] or the [source code][topics_0_code]. - -__Usage:__ `node topics.js --help` - -``` -topics.js - -Commands: - topics.js list Lists all topics in the current project. - topics.js create Creates a new topic. - topics.js delete Deletes a topic. - topics.js publish Publishes a message to a topic. - topics.js publish-batch Publishes messages to a topic using custom batching settings. - topics.js publish-ordered Publishes an ordered message to a topic. - topics.js get-policy Gets the IAM policy for a topic. - topics.js set-policy Sets the IAM policy for a topic. - topics.js test-permissions Tests the permissions for a topic. - -Options: - --version Show version number [boolean] - --help Show help [boolean] - -Examples: - node topics.js list - node topics.js create my-topic - node topics.js delete my-topic - node topics.js publish my-topic "Hello, world!" - node topics.js publish my-topic '{"data":"Hello, world!"}' - node topics.js publish-ordered my-topic "Hello, world!" - node topics.js publish-batch my-topic "Hello, world!" -w 1000 - node topics.js get-policy greetings - node topics.js set-policy greetings - node topics.js test-permissions greetings - -For more information, see https://cloud.google.com/pubsub/docs -``` - -[topics_0_docs]: https://cloud.google.com/pubsub/publisher -[topics_0_code]: topics.js - -### Subscriptions - -View the [documentation][subscriptions_1_docs] or the [source code][subscriptions_1_code]. - -__Usage:__ `node subscriptions.js --help` - -``` -subscriptions.js - -Commands: - subscriptions.js list [topicName] Lists all subscriptions in the current project, - optionally filtering by a topic. - subscriptions.js create Creates a new subscription. - subscriptions.js create-flow Creates a new subscription with flow-control limits, - which don't persist between subscriptions. - subscriptions.js create-push Creates a new push subscription. - subscriptions.js modify-config Modifies the configuration of an existing push - subscription. - subscriptions.js delete Deletes a subscription. - subscriptions.js get Gets the metadata for a subscription. - subscriptions.js listen-messages Listens to messages for a subscription. - subscriptions.js listen-errors Listens to messages and errors for a subscription. - subscriptions.js get-policy Gets the IAM policy for a subscription. - subscriptions.js set-policy Sets the IAM policy for a subscription. - subscriptions.js test-permissions Tests the permissions for a subscription. - -Options: - --version Show version number [boolean] - --help Show help [boolean] - -Examples: - node subscriptions.js list - node subscriptions.js list my-topic - node subscriptions.js create my-topic worker-1 - node subscriptions.js create-flow my-topic worker-1 -m 5 - node subscriptions.js create-push my-topic worker-1 - node subscriptions.js modify-config my-topic worker-1 - node subscriptions.js get worker-1 - node subscriptions.js listen-messages my-subscription - node subscriptions.js listen-errors my-subscription - node subscriptions.js delete worker-1 - node subscriptions.js pull worker-1 - node subscriptions.js get-policy worker-1 - node subscriptions.js set-policy worker-1 - node subscriptions.js test-permissions worker-1 - -For more information, see https://cloud.google.com/pubsub/docs -``` - -[subscriptions_1_docs]: https://cloud.google.com/pubsub/subscriber -[subscriptions_1_code]: subscriptions.js - -## Running the tests - -1. Set the **GCLOUD_PROJECT** and **GOOGLE_APPLICATION_CREDENTIALS** environment variables. - -1. Run the tests: - - With **npm**: - - npm test - - With **yarn**: - - yarn test +[client]: https://github.com/googleapis/nodejs-pubsub +[samples]: https://github.com/googleapis/nodejs-pubsub/tree/master/samples diff --git a/pubsub/package.json b/pubsub/package.json deleted file mode 100644 index b6a9dbe47d..0000000000 --- a/pubsub/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "nodejs-docs-samples-pubsub", - "version": "0.0.1", - "private": true, - "license": "Apache-2.0", - "author": "Google Inc.", - "repository": { - "type": "git", - "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" - }, - "engines": { - "node": ">=4.3.2" - }, - "scripts": { - "lint": "samples lint", - "pretest": "npm run lint", - "test": "samples test run --cmd ava -- -T 30s --verbose system-test/*.test.js" - }, - "dependencies": { - "@google-cloud/pubsub": "0.14.5", - "yargs": "10.0.3" - }, - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "2.0.11", - "ava": "0.22.0", - "proxyquire": "1.8.0", - "sinon": "4.0.1" - }, - "cloud-repo-tools": { - "requiresKeyFile": true, - "requiresProjectId": true, - "product": "pubsub", - "samples": [ - { - "id": "topics", - "name": "Topics", - "file": "topics.js", - "docs_link": "https://cloud.google.com/pubsub/publisher", - "usage": "node topics.js --help" - }, - { - "id": "subscriptions", - "name": "Subscriptions", - "file": "subscriptions.js", - "docs_link": "https://cloud.google.com/pubsub/subscriber", - "usage": "node subscriptions.js --help" - } - ] - } -} diff --git a/pubsub/quickstart.js b/pubsub/quickstart.js deleted file mode 100644 index eee7f7b0e6..0000000000 --- a/pubsub/quickstart.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -// [START pubsub_quickstart] -// Imports the Google Cloud client library -const PubSub = require('@google-cloud/pubsub'); - -// Your Google Cloud Platform project ID -const projectId = 'YOUR_PROJECT_ID'; - -// Instantiates a client -const pubsubClient = PubSub({ - projectId: projectId -}); - -// The name for the new topic -const topicName = 'my-new-topic'; - -// Creates the new topic -pubsubClient.createTopic(topicName) - .then((results) => { - const topic = results[0]; - console.log(`Topic ${topic.name} created.`); - }) - .catch((err) => { - console.error('ERROR:', err); - }); -// [END pubsub_quickstart] diff --git a/pubsub/subscriptions.js b/pubsub/subscriptions.js deleted file mode 100644 index 15ad1f224c..0000000000 --- a/pubsub/subscriptions.js +++ /dev/null @@ -1,539 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * This application demonstrates how to perform basic operations on - * subscriptions with the Google Cloud Pub/Sub API. - * - * For more information, see the README.md under /pubsub and the documentation - * at https://cloud.google.com/pubsub/docs. - */ - -'use strict'; - -const PubSub = require(`@google-cloud/pubsub`); - -// [START pubsub_list_subscriptions] -function listSubscriptions () { - // Instantiates a client - const pubsub = PubSub(); - - // Lists all subscriptions in the current project - return pubsub.getSubscriptions() - .then((results) => { - const subscriptions = results[0]; - - console.log('Subscriptions:'); - subscriptions.forEach((subscription) => console.log(subscription.name)); - - return subscriptions; - }); -} -// [END pubsub_list_subscriptions] - -// [START pubsub_list_topic_subscriptions] -function listTopicSubscriptions (topicName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Lists all subscriptions for the topic - return topic.getSubscriptions() - .then((results) => { - const subscriptions = results[0]; - - console.log(`Subscriptions for ${topicName}:`); - subscriptions.forEach((subscription) => console.log(subscription.name)); - - return subscriptions; - }); -} -// [END pubsub_list_topic_subscriptions] - -// [START pubsub_create_subscription] -function createSubscription (topicName, subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Creates a new subscription, e.g. "my-new-subscription" - return topic.createSubscription(subscriptionName) - .then((results) => { - const subscription = results[0]; - - console.log(`Subscription ${subscription.name} created.`); - - return subscription; - }); -} -// [END pubsub_create_subscription] - -// [START pubsub_subscriber_flow_settings] -function createFlowControlledSubscription (topicName, subscriptionName, maxInProgress, maxBytes) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Creates a new subscription, e.g. "my-new-subscription" - // Note that flow control configurations are not persistent - return topic.createSubscription(subscriptionName, { - flowControl: { - maxBytes: maxBytes, - maxMessages: maxInProgress - } - }) - .then((results) => { - const subscription = results[0]; - - console.log(`Subscription ${subscription.name} created with a maximum of ${maxInProgress} unprocessed messages.`); - - return subscription; - }); -} -// [END pubsub_subscriber_flow_settings] - -// [START pubsub_create_push_subscription] -function createPushSubscription (topicName, subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - const options = { - pushConfig: { - // Set to an HTTPS endpoint of your choice. If necessary, register - // (authorize) the domain on which the server is hosted. - pushEndpoint: `https://${pubsub.projectId}.appspot.com/push` - } - }; - - // Creates a new push subscription, e.g. "my-new-subscription" - return topic.createSubscription(subscriptionName, options) - .then((results) => { - const subscription = results[0]; - - console.log(`Subscription ${subscription.name} created.`); - - return subscription; - }); -} -// [END pubsub_create_push_subscription] - -// [START pubsub_modify_push_config] -function modifyPushConfig (topicName, subscriptionName, pushEndpoint) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic and subscription, e.g. "my-topic" > "my-subscription" - const topic = pubsub.topic(topicName); - const subscription = topic.subscription(subscriptionName); - - const options = { - // Set to an HTTPS endpoint of your choice. If necessary, register - // (authorize) the domain on which the server is hosted. - pushEndpoint: `https://${pubsub.projectId}.appspot.com/push` - }; - - return subscription.modifyPushConfig(options) - .then((results) => { - console.log(`Modified push config for subscription ${subscription.name}.`); - }); -} -// [END pubsub_modify_push_config] - -// [START pubsub_delete_subscription] -function deleteSubscription (subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // Deletes the subscription - return subscription.delete() - .then(() => { - console.log(`Subscription ${subscription.name} deleted.`); - }); -} -// [END pubsub_delete_subscription] - -// [START pubsub_get_subscription] -function getSubscription (subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // Gets the metadata for the subscription - return subscription.getMetadata() - .then((results) => { - const metadata = results[0]; - - console.log(`Subscription: ${metadata.name}`); - console.log(`Topic: ${metadata.topic}`); - console.log(`Push config: ${metadata.pushConfig.pushEndpoint}`); - console.log(`Ack deadline: ${metadata.ackDeadlineSeconds}s`); - - return metadata; - }); -} -// [END pubsub_get_subscription] - -// [START pubsub_listen_messages] -function listenForMessages (subscriptionName, timeout) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // Create an event handler to handle messages - let messageCount = 0; - const messageHandler = (message) => { - console.log(`Received message ${message.id}:`); - console.log(`\tData: ${message.data}`); - console.log(`\tAttributes: ${message.attributes}`); - messageCount += 1; - - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; - - // Listen for new messages until timeout is hit - subscription.on(`message`, messageHandler); - setTimeout(() => { - subscription.removeListener('message', messageHandler); - console.log(`${messageCount} message(s) received.`); - }, timeout * 1000); -} -// [END pubsub_listen_messages] - -let subscribeCounterValue = 1; - -function getSubscribeCounterValue () { - return subscribeCounterValue; -} - -function setSubscribeCounterValue (value) { - subscribeCounterValue = value; -} - -// [START pubsub_listen_ordered_messages] -const outstandingMessages = {}; - -function listenForOrderedMessages (subscriptionName, timeout) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // Create an event handler to handle messages - const messageHandler = function (message) { - // Buffer the message in an object (for later ordering) - outstandingMessages[message.attributes.counterId] = message; - - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; - - // Listen for new messages until timeout is hit - return new Promise((resolve) => { - subscription.on(`message`, messageHandler); - setTimeout(() => { - subscription.removeListener(`message`, messageHandler); - resolve(); - }, timeout * 1000); - }) - .then(() => { - // Pub/Sub messages are unordered, so here we manually order messages by - // their "counterId" attribute which was set when they were published. - const outstandingIds = Object.keys(outstandingMessages).map((counterId) => parseInt(counterId, 10)); - outstandingIds.sort(); - - outstandingIds.forEach((counterId) => { - const counter = getSubscribeCounterValue(); - const message = outstandingMessages[counterId]; - - if (counterId < counter) { - // The message has already been processed - message.ack(); - delete outstandingMessages[counterId]; - } else if (counterId === counter) { - // Process the message - console.log(`* %d %j %j`, message.id, message.data.toString(), message.attributes); - setSubscribeCounterValue(counterId + 1); - message.ack(); - delete outstandingMessages[counterId]; - } else { - // Have not yet processed the message on which this message is dependent - return false; - } - }); - }); -} -// [END pubsub_listen_ordered_messages] - -// [START pubsub_listen_errors] -function listenForErrors (subscriptionName, timeout) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // Create an event handler to handle messages - const messageHandler = function (message) { - // Do something with the message - console.log(`Message: ${message}`); - - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; - - // Create an event handler to handle errors - const errorHandler = function (error) { - // Do something with the error - console.error(`ERROR: ${error}`); - }; - - // Listen for new messages/errors until timeout is hit - return new Promise((resolve) => { - subscription.on(`message`, messageHandler); - subscription.on(`error`, errorHandler); - setTimeout(() => { - subscription.removeListener(`message`, messageHandler); - subscription.removeListener(`error`, errorHandler); - resolve(); - }, timeout * 1000); - }); -} -// [END pubsub_listen_errors] - -// [START pubsub_get_subscription_policy] -function getSubscriptionPolicy (subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // Retrieves the IAM policy for the subscription - return subscription.iam.getPolicy() - .then((results) => { - const policy = results[0]; - - console.log(`Policy for subscription: %j.`, policy.bindings); - - return policy; - }); -} -// [END pubsub_get_subscription_policy] - -// [START pubsub_set_subscription_policy] -function setSubscriptionPolicy (subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - // The new IAM policy - const newPolicy = { - bindings: [ - { - // Add a group as editors - role: `roles/pubsub.editor`, - members: [`group:cloud-logs@google.com`] - }, - { - // Add all users as viewers - role: `roles/pubsub.viewer`, - members: [`allUsers`] - } - ] - }; - - // Updates the IAM policy for the subscription - return subscription.iam.setPolicy(newPolicy) - .then((results) => { - const updatedPolicy = results[0]; - - console.log(`Updated policy for subscription: %j`, updatedPolicy.bindings); - - return updatedPolicy; - }); -} -// [END pubsub_set_subscription_policy] - -// [START pubsub_test_subscription_permissions] -function testSubscriptionPermissions (subscriptionName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing subscription, e.g. "my-subscription" - const subscription = pubsub.subscription(subscriptionName); - - const permissionsToTest = [ - `pubsub.subscriptions.consume`, - `pubsub.subscriptions.update` - ]; - - // Tests the IAM policy for the specified subscription - subscription.iam.testPermissions(permissionsToTest) - .then((results) => { - const permissions = results[0]; - - console.log(`Tested permissions for subscription: %j`, permissions); - - return permissions; - }); -} -// [END pubsub_test_subscription_permissions] - -module.exports = { listenForOrderedMessages }; - -const cli = require(`yargs`) - .demand(1) - .command( - `list [topicName]`, - `Lists all subscriptions in the current project, optionally filtering by a topic.`, - {}, - (opts) => { - if (opts.topicName) { - listTopicSubscriptions(opts.topicName); - } else { - listSubscriptions(); - } - } - ) - .command( - `create `, - `Creates a new subscription.`, - {}, - (opts) => createSubscription(opts.topicName, opts.subscriptionName) - ) - .command( - `create-flow `, - `Creates a new subscription with flow-control limits, which don't persist between subscriptions.`, - { - maxInProgress: { - alias: 'm', - type: 'number', - default: 0 - }, - maxBytes: { - alias: 'b', - type: 'number', - default: 0 - } - }, - (opts) => createFlowControlledSubscription(opts.topicName, opts.subscriptionName, opts.maxInProgress, opts.maxBytes) - ) - .command( - `create-push `, - `Creates a new push subscription.`, - {}, - (opts) => createPushSubscription(opts.topicName, opts.subscriptionName) - ) - .command( - `modify-config `, - `Modifies the configuration of an existing push subscription.`, - {}, - (opts) => modifyPushConfig(opts.topicName, opts.subscriptionName) - ) - .command( - `delete `, - `Deletes a subscription.`, - {}, - (opts) => deleteSubscription(opts.subscriptionName) - ) - .command( - `get `, - `Gets the metadata for a subscription.`, - {}, - (opts) => getSubscription(opts.subscriptionName) - ) - .command( - `listen-messages `, - `Listens to messages for a subscription.`, - { - timeout: { - alias: 't', - type: 'number', - default: 10 - } - }, - (opts) => listenForMessages(opts.subscriptionName, opts.timeout) - ) - .command( - `listen-errors `, - `Listens to messages and errors for a subscription.`, - { - timeout: { - alias: 't', - type: 'number', - default: 10 - } - }, - (opts) => listenForErrors(opts.subscriptionName, opts.timeout) - ) - .command( - `get-policy `, - `Gets the IAM policy for a subscription.`, - {}, - (opts) => getSubscriptionPolicy(opts.subscriptionName) - ) - .command( - `set-policy `, - `Sets the IAM policy for a subscription.`, - {}, - (opts) => setSubscriptionPolicy(opts.subscriptionName) - ) - .command( - `test-permissions `, - `Tests the permissions for a subscription.`, - {}, - (opts) => testSubscriptionPermissions(opts.subscriptionName) - ) - .example(`node $0 list`) - .example(`node $0 list my-topic`) - .example(`node $0 create my-topic worker-1`) - .example(`node $0 create-flow my-topic worker-1 -m 5`) - .example(`node $0 create-push my-topic worker-1`) - .example(`node $0 modify-config my-topic worker-1`) - .example(`node $0 get worker-1`) - .example(`node $0 listen-messages my-subscription`) - .example(`node $0 listen-errors my-subscription`) - .example(`node $0 delete worker-1`) - .example(`node $0 pull worker-1`) - .example(`node $0 get-policy worker-1`) - .example(`node $0 set-policy worker-1`) - .example(`node $0 test-permissions worker-1`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/pubsub/docs`); - -if (module === require.main) { - cli.help().strict().argv; // eslint-disable-line -} diff --git a/pubsub/system-test/quickstart.test.js b/pubsub/system-test/quickstart.test.js deleted file mode 100644 index 819ef9e566..0000000000 --- a/pubsub/system-test/quickstart.test.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noPreserveCache(); -const pubsub = proxyquire(`@google-cloud/pubsub`, {})(); -const sinon = require(`sinon`); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); -const uuid = require(`uuid`); - -const topicName = `nodejs-docs-samples-test-${uuid.v4()}`; -const projectId = process.env.GCLOUD_PROJECT; -const fullTopicName = `projects/${projectId}/topics/${topicName}`; - -test.before(tools.stubConsole); -test.after.always(() => { - tools.restoreConsole(); - return pubsub.topic(topicName).delete().catch(() => {}); -}); - -test.cb(`should create a topic`, (t) => { - const expectedTopicName = `my-new-topic`; - const pubsubMock = { - createTopic: (_topicName) => { - t.is(_topicName, expectedTopicName); - - return pubsub.createTopic(topicName) - .then(([topic]) => { - t.is(topic.name, fullTopicName); - - setTimeout(() => { - try { - t.is(console.log.callCount, 1); - t.deepEqual(console.log.getCall(0).args, [`Topic ${topic.name} created.`]); - t.end(); - } catch (err) { - t.end(err); - } - }, 200); - - return [topic]; - }); - } - }; - - proxyquire(`../quickstart`, { - '@google-cloud/pubsub': sinon.stub().returns(pubsubMock) - }); -}); diff --git a/pubsub/system-test/subscriptions.test.js b/pubsub/system-test/subscriptions.test.js deleted file mode 100644 index 7b8f2325cd..0000000000 --- a/pubsub/system-test/subscriptions.test.js +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const path = require(`path`); -const pubsub = require(`@google-cloud/pubsub`)(); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); -const uuid = require(`uuid`); - -const cwd = path.join(__dirname, `..`); -const topicNameOne = `nodejs-docs-samples-test-${uuid.v4()}`; -const topicNameTwo = `nodejs-docs-samples-test-${uuid.v4()}`; -const subscriptionNameOne = `nodejs-docs-samples-test-sub-${uuid.v4()}`; -const subscriptionNameTwo = `nodejs-docs-samples-test-sub-${uuid.v4()}`; -const subscriptionNameThree = `nodejs-docs-samples-test-sub-${uuid.v4()}`; -const subscriptionNameFour = `nodejs-docs-samples-test-sub-${uuid.v4()}`; -const projectId = process.env.GCLOUD_PROJECT; -const fullTopicNameOne = `projects/${projectId}/topics/${topicNameOne}`; -const fullSubscriptionNameOne = `projects/${projectId}/subscriptions/${subscriptionNameOne}`; -const fullSubscriptionNameTwo = `projects/${projectId}/subscriptions/${subscriptionNameTwo}`; -const fullSubscriptionNameFour = `projects/${projectId}/subscriptions/${subscriptionNameFour}`; -const cmd = `node subscriptions.js`; - -test.before(tools.checkCredentials); -test.before(async () => { - await Promise.all([ - pubsub.createTopic(topicNameOne), - pubsub.createTopic(topicNameTwo) - ]); -}); - -test.after.always(async () => { - try { - await pubsub.subscription(subscriptionNameOne).delete(); - } catch (err) {} // ignore error - try { - await pubsub.subscription(subscriptionNameTwo).delete(); - } catch (err) {} // ignore error - try { - await pubsub.subscription(subscriptionNameThree).delete(); - } catch (err) {} // ignore error - try { - await pubsub.topic(topicNameOne).delete(); - } catch (err) {} // ignore error - try { - await pubsub.topic(topicNameTwo).delete(); - } catch (err) {} // ignore error -}); - -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); - -test.serial(`should create a subscription`, async (t) => { - t.plan(1); - const output = await tools.runAsync(`${cmd} create ${topicNameOne} ${subscriptionNameOne}`, cwd); - t.is(output, `Subscription ${fullSubscriptionNameOne} created.`); - await tools.tryTest(async (assert) => { - const [subscriptions] = await pubsub.topic(topicNameOne).getSubscriptions(); - assert.equal(subscriptions[0].name, fullSubscriptionNameOne); - }).start(); -}); - -test.serial(`should create a push subscription`, async (t) => { - const output = await tools.runAsync(`${cmd} create-push ${topicNameOne} ${subscriptionNameTwo}`, cwd); - t.is(output, `Subscription ${fullSubscriptionNameTwo} created.`); - await tools.tryTest(async (assert) => { - const [subscriptions] = await pubsub.topic(topicNameOne).getSubscriptions(); - assert(subscriptions.some((s) => s.name === fullSubscriptionNameTwo)); - }).start(); -}); - -test.serial(`should modify the config of an existing push subscription`, async (t) => { - t.plan(1); - const output = await tools.runAsync(`${cmd} modify-config ${topicNameTwo} ${subscriptionNameTwo}`, cwd); - t.is(output, `Modified push config for subscription ${fullSubscriptionNameTwo}.`); -}); - -test.serial(`should get metadata for a subscription`, async (t) => { - const output = await tools.runAsync(`${cmd} get ${subscriptionNameOne}`, cwd); - const expected = `Subscription: ${fullSubscriptionNameOne}` + - `\nTopic: ${fullTopicNameOne}` + - `\nPush config: ` + - `\nAck deadline: 10s`; - t.is(output, expected); -}); - -test.serial(`should list all subscriptions`, async (t) => { - t.plan(0); - await tools.tryTest(async (assert) => { - const output = await tools.runAsync(`${cmd} list`, cwd); - assert(output.includes(`Subscriptions:`)); - assert(output.includes(fullSubscriptionNameOne)); - assert(output.includes(fullSubscriptionNameTwo)); - }).start(); -}); - -test.serial(`should list subscriptions for a topic`, async (t) => { - t.plan(0); - await tools.tryTest(async (assert) => { - const output = await tools.runAsync(`${cmd} list ${topicNameOne}`, cwd); - assert(output.includes(`Subscriptions for ${topicNameOne}:`)); - assert(output.includes(fullSubscriptionNameOne)); - assert(output.includes(fullSubscriptionNameTwo)); - }).start(); -}); - -test.serial(`should listen for messages`, async (t) => { - const messageIds = await pubsub.topic(topicNameOne).publisher().publish(Buffer.from(`Hello, world!`)); - const output = await tools.runAsync(`${cmd} listen-messages ${subscriptionNameOne}`, cwd); - t.true(output.includes(`Received message ${messageIds[0]}:`)); -}); - -test.serial(`should listen for ordered messages`, async (t) => { - const timeout = 5; - const subscriptions = require('../subscriptions'); - const expected = `Hello, world!`; - const expectedBuffer = Buffer.from(expected); - const publishedMessageIds = []; - const publisherTwo = pubsub.topic(topicNameTwo).publisher(); - - await pubsub.topic(topicNameTwo).createSubscription(subscriptionNameThree); - let [result] = await publisherTwo.publish(expectedBuffer, { counterId: '3' }); - publishedMessageIds.push(result); - await subscriptions.listenForOrderedMessages(subscriptionNameThree, timeout); - t.is(console.log.callCount, 0); - - [result] = await publisherTwo.publish(expectedBuffer, { counterId: '1' }); - publishedMessageIds.push(result); - await subscriptions.listenForOrderedMessages(subscriptionNameThree, timeout); - t.is(console.log.callCount, 1); - t.deepEqual(console.log.firstCall.args, [`* %d %j %j`, publishedMessageIds[1], expected, { counterId: '1' }]); - - [result] = await publisherTwo.publish(expectedBuffer, { counterId: '1' }); - [result] = await publisherTwo.publish(expectedBuffer, { counterId: '2' }); - publishedMessageIds.push(result); - await tools.tryTest(async (assert) => { - await subscriptions.listenForOrderedMessages(subscriptionNameThree, timeout); - assert.equal(console.log.callCount, 3); - assert.deepEqual(console.log.secondCall.args, [`* %d %j %j`, publishedMessageIds[2], expected, { counterId: '2' }]); - assert.deepEqual(console.log.thirdCall.args, [`* %d %j %j`, publishedMessageIds[0], expected, { counterId: '3' }]); - }); -}); - -test.serial(`should listen for error messages`, async (t) => { - const output = await tools.runAsyncWithIO(`${cmd} listen-errors nonexistent-subscription -t 3`, cwd); - t.true(output.stderr.includes(`Resource not found`)); -}); - -test.serial(`should set the IAM policy for a subscription`, async (t) => { - await tools.runAsync(`${cmd} set-policy ${subscriptionNameOne}`, cwd); - const results = await pubsub.subscription(subscriptionNameOne).iam.getPolicy(); - const policy = results[0]; - t.deepEqual(policy.bindings, [ - { - role: `roles/pubsub.editor`, - members: [`group:cloud-logs@google.com`] - }, - { - role: `roles/pubsub.viewer`, - members: [`allUsers`] - } - ]); -}); - -test.serial(`should get the IAM policy for a subscription`, async (t) => { - const results = await pubsub.subscription(subscriptionNameOne).iam.getPolicy(); - const output = await tools.runAsync(`${cmd} get-policy ${subscriptionNameOne}`, cwd); - t.is(output, `Policy for subscription: ${JSON.stringify(results[0].bindings)}.`); -}); - -test.serial(`should test permissions for a subscription`, async (t) => { - const output = await tools.runAsync(`${cmd} test-permissions ${subscriptionNameOne}`, cwd); - t.true(output.includes(`Tested permissions for subscription`)); -}); - -test.serial(`should delete a subscription`, async (t) => { - t.plan(1); - const output = await tools.runAsync(`${cmd} delete ${subscriptionNameOne}`, cwd); - t.is(output, `Subscription ${fullSubscriptionNameOne} deleted.`); - await tools.tryTest(async (assert) => { - const [subscriptions] = await pubsub.getSubscriptions(); - assert.ok(subscriptions); - assert(subscriptions.every((s) => s.name !== fullSubscriptionNameOne)); - }).start(); -}); - -test.serial(`should create a subscription with flow control`, async (t) => { - t.plan(1); - const output = await tools.runAsync(`${cmd} create-flow ${topicNameTwo} ${subscriptionNameFour} -m 5 -b 1024`, cwd); - t.is(output, `Subscription ${fullSubscriptionNameFour} created with a maximum of 5 unprocessed messages.`); - await tools.tryTest(async (assert) => { - const [subscriptions] = await pubsub.topic(topicNameTwo).getSubscriptions(); - assert(subscriptions.some((s) => s.name === fullSubscriptionNameFour)); - }).start(); -}); diff --git a/pubsub/system-test/topics.test.js b/pubsub/system-test/topics.test.js deleted file mode 100644 index 2e0844c708..0000000000 --- a/pubsub/system-test/topics.test.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const path = require(`path`); -const pubsub = require(`@google-cloud/pubsub`)(); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); -const uuid = require(`uuid`); - -const cwd = path.join(__dirname, `..`); -const topicNameOne = `nodejs-docs-samples-test-${uuid.v4()}`; -const topicNameTwo = `nodejs-docs-samples-test-${uuid.v4()}`; -const subscriptionNameOne = `nodejs-docs-samples-test-${uuid.v4()}`; -const subscriptionNameTwo = `nodejs-docs-samples-test-${uuid.v4()}`; -const subscriptionNameThree = `nodejs-docs-samples-test-${uuid.v4()}`; -const projectId = process.env.GCLOUD_PROJECT; -const fullTopicNameOne = `projects/${projectId}/topics/${topicNameOne}`; -const expectedMessage = { data: `Hello, world!` }; -const cmd = `node topics.js`; - -test.before(tools.checkCredentials); -test.before(async () => { - try { - await pubsub.createTopic(topicNameTwo); - } catch (err) {} // ignore error -}); - -test.after.always(async () => { - try { - await pubsub.subscription(subscriptionNameOne).delete(); - } catch (err) {} // ignore error - try { - await pubsub.topic(topicNameOne).delete(); - } catch (err) {} // ignore error - try { - await pubsub.subscription(subscriptionNameTwo).delete(); - } catch (err) {} // ignore error - try { - await pubsub.subscription(subscriptionNameThree).delete(); - } catch (err) {} // ignore error - try { - await pubsub.topic(topicNameTwo).delete(); - } catch (err) {} // ignore error -}); - -// Helper function to pull one message -const _pullOneMessage = (subscriptionObj, timeout) => { - timeout = timeout || 10000; // 10 second timeout by default - - let message; - return new Promise((resolve, reject) => { - // First message received; ack it + resolve promise - const messageHandler = (received) => { - received.ack(); - message = received; - return resolve(messageHandler); - }; - - // Listen for new messages - subscriptionObj.on(`message`, messageHandler); - - // Timeout appropriately - setTimeout(() => { - return reject(new Error(`_pullOneMessage timed out`)); - }, timeout); - }).then((messageHandler) => { - subscriptionObj.removeListener('message', messageHandler); - return Promise.resolve(message); - }); -}; - -test.serial(`should create a topic`, async (t) => { - t.plan(1); - const output = await tools.runAsync(`${cmd} create ${topicNameOne}`, cwd); - t.is(output, `Topic ${fullTopicNameOne} created.`); - await tools.tryTest(async (assert) => { - const [topics] = await pubsub.getTopics(); - assert(topics.some((s) => s.name === fullTopicNameOne)); - }).start(); -}); - -test.serial(`should list topics`, async (t) => { - await tools.tryTest(async () => { - const output = await tools.runAsync(`${cmd} list`, cwd); - t.true(output.includes(`Topics:`)); - t.true(output.includes(fullTopicNameOne)); - }).start(); -}); - -test.serial(`should publish a simple message`, async (t) => { - t.plan(1); - const [subscription] = await pubsub.topic(topicNameOne).createSubscription(subscriptionNameOne); - await tools.runAsync(`${cmd} publish ${topicNameOne} "${expectedMessage.data}"`, cwd); - const receivedMessage = await _pullOneMessage(subscription); - t.is(receivedMessage.data.toString(), expectedMessage.data); -}); - -test.serial(`should publish a JSON message`, async (t) => { - const [subscription] = await pubsub.topic(topicNameOne).createSubscription(subscriptionNameOne); - await tools.runAsync(`${cmd} publish ${topicNameOne} '${JSON.stringify(expectedMessage)}'`, cwd); - const receivedMessage = await _pullOneMessage(subscription); - t.deepEqual(JSON.parse(receivedMessage.data.toString()), expectedMessage); -}); - -test.serial(`should publish ordered messages`, async (t) => { - const topics = require(`../topics`); - - const [subscription] = await pubsub.topic(topicNameTwo).createSubscription(subscriptionNameTwo); - - let messageId = await topics.publishOrderedMessage(topicNameTwo, expectedMessage.data); - let message = await _pullOneMessage(subscription); - t.is(message.id, messageId); - t.is(message.data.toString(), expectedMessage.data); - t.is(message.attributes.counterId, '1'); - - messageId = await topics.publishOrderedMessage(topicNameTwo, expectedMessage.data); - message = await _pullOneMessage(subscription); - t.is(message.id, messageId); - t.is(message.data.toString(), expectedMessage.data); - t.is(message.attributes.counterId, '2'); - await topics.publishOrderedMessage(topicNameTwo, expectedMessage.data); -}); - -test.serial(`should publish with specific batch settings`, async (t) => { - t.plan(2); - const expectedWait = 1000; - const [subscription] = await pubsub.topic(topicNameOne).createSubscription(subscriptionNameThree); - const startTime = Date.now(); - await tools.runAsync(`${cmd} publish-batch ${topicNameOne} "${expectedMessage.data}" -w ${expectedWait}`, cwd); - const receivedMessage = await _pullOneMessage(subscription); - const publishTime = Date.parse(receivedMessage.publishTime); - t.is(receivedMessage.data.toString(), expectedMessage.data); - t.true(publishTime - startTime > expectedWait); -}); - -test.serial(`should set the IAM policy for a topic`, async (t) => { - await tools.runAsync(`${cmd} set-policy ${topicNameOne}`, cwd); - const results = await pubsub.topic(topicNameOne).iam.getPolicy(); - const [policy] = results; - t.deepEqual(policy.bindings, [ - { - role: `roles/pubsub.editor`, - members: [`group:cloud-logs@google.com`] - }, - { - role: `roles/pubsub.viewer`, - members: [`allUsers`] - } - ]); -}); - -test.serial(`should get the IAM policy for a topic`, async (t) => { - const [policy] = await pubsub.topic(topicNameOne).iam.getPolicy(); - const output = await tools.runAsync(`${cmd} get-policy ${topicNameOne}`, cwd); - t.is(output, `Policy for topic: ${JSON.stringify(policy.bindings)}.`); -}); - -test.serial(`should test permissions for a topic`, async (t) => { - const output = await tools.runAsync(`${cmd} test-permissions ${topicNameOne}`, cwd); - t.true(output.includes(`Tested permissions for topic`)); -}); - -test.serial(`should delete a topic`, async (t) => { - t.plan(1); - const output = await tools.runAsync(`${cmd} delete ${topicNameOne}`, cwd); - t.is(output, `Topic ${fullTopicNameOne} deleted.`); - await tools.tryTest(async (assert) => { - const [topics] = await pubsub.getTopics(); - assert(topics.every((s) => s.name !== fullTopicNameOne)); - }).start(); -}); diff --git a/pubsub/topics.js b/pubsub/topics.js deleted file mode 100644 index 9d4363f7de..0000000000 --- a/pubsub/topics.js +++ /dev/null @@ -1,353 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * This application demonstrates how to perform basic operations on topics with - * the Google Cloud Pub/Sub API. - * - * For more information, see the README.md under /pubsub and the documentation - * at https://cloud.google.com/pubsub/docs. - */ - -'use strict'; - -const PubSub = require(`@google-cloud/pubsub`); - -// [START pubsub_list_topics] -function listAllTopics () { - // Instantiates a client - const pubsub = PubSub(); - - // Lists all topics in the current project - return pubsub.getTopics() - .then((results) => { - const topics = results[0]; - - console.log('Topics:'); - topics.forEach((topic) => console.log(topic.name)); - - return topics; - }); -} -// [END pubsub_list_topics] - -// [START pubsub_create_topic] -function createTopic (topicName) { - // Instantiates a client - const pubsub = PubSub(); - - // Creates a new topic, e.g. "my-new-topic" - return pubsub.createTopic(topicName) - .then((results) => { - const topic = results[0]; - - console.log(`Topic ${topic.name} created.`); - - return topic; - }); -} -// [END pubsub_create_topic] - -// [START pubsub_delete_topic] -function deleteTopic (topicName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Deletes the topic - return topic.delete() - .then(() => { - console.log(`Topic ${topic.name} deleted.`); - }); -} -// [END pubsub_delete_topic] - -// [START pubsub_publish_message] -function publishMessage (topicName, data) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Create a publisher for the topic (which can include additional batching configuration) - const publisher = topic.publisher(); - - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); - return publisher.publish(dataBuffer) - .then((results) => { - const messageId = results[0]; - - console.log(`Message ${messageId} published.`); - - return messageId; - }); -} -// [END pubsub_publish_message] - -// [START pubsub_publisher_batched_settings] -function publishBatchedMessages (topicName, data, maxMessages, maxWaitTime) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Create a publisher for the topic (with additional batching configuration) - const publisher = topic.publisher({ - batching: { - maxMessages: maxMessages, - maxMilliseconds: maxWaitTime - } - }); - - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); - return publisher.publish(dataBuffer) - .then((results) => { - const messageId = results[0]; - - console.log(`Message ${messageId} published.`); - - return messageId; - }); -} -// [END pubsub_publisher_batched_settings] - -let publishCounterValue = 1; - -function getPublishCounterValue () { - return publishCounterValue; -} - -function setPublishCounterValue (value) { - publishCounterValue = value; -} - -// [START pubsub_publish_ordered_message] -function publishOrderedMessage (topicName, data) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Create a publisher for the topic (which can include additional batching configuration) - const publisher = topic.publisher(); - - // Creates message parameters - const dataBuffer = Buffer.from(data); - const attributes = { - // Pub/Sub messages are unordered, so assign an order ID and manually order messages - counterId: `${getPublishCounterValue()}` - }; - - // Publishes the message - return publisher.publish(dataBuffer, attributes) - .then((results) => { - const messageId = results[0]; - - // Update the counter value - setPublishCounterValue(parseInt(attributes.counterId, 10) + 1); - - console.log(`Message ${messageId} published.`); - - return messageId; - }); -} -// [END pubsub_publish_ordered_message] - -// [START pubsub_get_topic_policy] -function getTopicPolicy (topicName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // Retrieves the IAM policy for the topic - return topic.iam.getPolicy() - .then((results) => { - const policy = results[0]; - - console.log(`Policy for topic: %j.`, policy.bindings); - - return policy; - }); -} -// [END pubsub_get_topic_policy] - -// [START pubsub_set_topic_policy] -function setTopicPolicy (topicName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - // The new IAM policy - const newPolicy = { - bindings: [ - { - // Add a group as editors - role: `roles/pubsub.editor`, - members: [`group:cloud-logs@google.com`] - }, - { - // Add all users as viewers - role: `roles/pubsub.viewer`, - members: [`allUsers`] - } - ] - }; - - // Updates the IAM policy for the topic - return topic.iam.setPolicy(newPolicy) - .then((results) => { - const updatedPolicy = results[0]; - - console.log(`Updated policy for topic: %j`, updatedPolicy.bindings); - - return updatedPolicy; - }); -} -// [END pubsub_set_topic_policy] - -// [START pubsub_test_topic_permissions] -function testTopicPermissions (topicName) { - // Instantiates a client - const pubsub = PubSub(); - - // References an existing topic, e.g. "my-topic" - const topic = pubsub.topic(topicName); - - const permissionsToTest = [ - `pubsub.topics.attachSubscription`, - `pubsub.topics.publish`, - `pubsub.topics.update` - ]; - - // Tests the IAM policy for the specified topic - return topic.iam.testPermissions(permissionsToTest) - .then((results) => { - const permissions = results[0]; - - console.log(`Tested permissions for topic: %j`, permissions); - - return permissions; - }); -} -// [END pubsub_test_topic_permissions] - -module.exports = { publishOrderedMessage }; - -const cli = require(`yargs`) - .demand(1) - .command( - `list`, - `Lists all topics in the current project.`, - {}, - listAllTopics - ) - .command( - `create `, - `Creates a new topic.`, - {}, - (opts) => createTopic(opts.topicName) - ) - .command( - `delete `, - `Deletes a topic.`, - {}, - (opts) => deleteTopic(opts.topicName) - ) - .command( - `publish `, - `Publishes a message to a topic.`, - {}, - (opts) => { - publishMessage(opts.topicName, opts.message); - } - ) - .command( - `publish-batch `, - `Publishes messages to a topic using custom batching settings.`, - { - maxWaitTime: { - alias: 'w', - type: 'number', - default: 10 - }, - maxMessages: { - alias: 'm', - type: 'number', - default: 10 - } - }, - (opts) => { - publishBatchedMessages(opts.topicName, opts.message, opts.maxMessages, opts.maxWaitTime); - } - ) - .command( - `publish-ordered `, - `Publishes an ordered message to a topic.`, - {}, - (opts) => { - try { - opts.message = JSON.parse(opts.message); - } catch (err) { - // Ignore error - } - publishOrderedMessage(opts.topicName, opts.message); - } - ) - .command( - `get-policy `, - `Gets the IAM policy for a topic.`, - {}, - (opts) => getTopicPolicy(opts.topicName) - ) - .command( - `set-policy `, - `Sets the IAM policy for a topic.`, - {}, - (opts) => setTopicPolicy(opts.topicName) - ) - .command( - `test-permissions `, - `Tests the permissions for a topic.`, - {}, - (opts) => testTopicPermissions(opts.topicName) - ) - .example(`node $0 list`) - .example(`node $0 create my-topic`) - .example(`node $0 delete my-topic`) - .example(`node $0 publish my-topic "Hello, world!"`) - .example(`node $0 publish my-topic '{"data":"Hello, world!"}'`) - .example(`node $0 publish-ordered my-topic "Hello, world!"`) - .example(`node $0 publish-batch my-topic "Hello, world!" -w 1000`) - .example(`node $0 get-policy greetings`) - .example(`node $0 set-policy greetings`) - .example(`node $0 test-permissions greetings`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/pubsub/docs`); - -if (module === require.main) { - cli.help().strict().argv; // eslint-disable-line -}