├── .eslintignore ├── .eslintrc.json ├── .gitattributes ├── .github ├── .OwlBot.lock.yaml ├── .OwlBot.yaml ├── .header-checker-lint.yaml ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── config.yml │ ├── documentation_request.yml │ ├── feature_request.yml │ ├── processs_request.md │ ├── questions.md │ └── support_request.md ├── PULL_REQUEST_TEMPLATE.md ├── auto-approve.yml ├── auto-label.yaml ├── generated-files-bot.yml ├── release-please.yml ├── release-trigger.yml ├── scripts │ ├── close-invalid-link.cjs │ ├── close-unresponsive.cjs │ ├── fixtures │ │ ├── invalidIssueBody.txt │ │ ├── validIssueBody.txt │ │ └── validIssueBodyDifferentLinkLocation.txt │ ├── package.json │ ├── remove-response-label.cjs │ └── tests │ │ ├── close-invalid-link.test.cjs │ │ └── close-or-remove-response-label.test.cjs ├── sync-repo-settings.yaml └── workflows │ ├── ci.yaml │ ├── issues-no-repro.yaml │ └── response.yaml ├── .gitignore ├── .jsdoc.js ├── .kokoro ├── .gitattributes ├── common.cfg ├── continuous │ └── node18 │ │ ├── common.cfg │ │ ├── lint.cfg │ │ ├── samples-test.cfg │ │ ├── system-test.cfg │ │ └── test.cfg ├── docs.sh ├── lint.sh ├── populate-secrets.sh ├── presubmit │ ├── node18 │ │ ├── common.cfg │ │ ├── samples-test.cfg │ │ ├── system-test.cfg │ │ └── test.cfg │ └── windows │ │ ├── common.cfg │ │ └── test.cfg ├── publish.sh ├── release │ ├── common.cfg │ ├── docs-devsite.cfg │ ├── docs-devsite.sh │ ├── docs.cfg │ ├── docs.sh │ └── publish.cfg ├── samples-test.sh ├── system-test.sh ├── test.bat ├── test.sh ├── trampoline.sh └── trampoline_v2.sh ├── .mocharc.js ├── .mocharc.json ├── .nycrc ├── .prettierignore ├── .prettierrc.js ├── .readme-partials.yml ├── .repo-metadata.json ├── .trampolinerc ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── bin ├── README.md ├── benchwrapper.js └── pubsub.proto ├── helperMethods.ts.tmpl ├── linkinator.config.json ├── owlbot.py ├── package.json ├── protos ├── google │ ├── cloud │ │ └── common_resources.proto │ └── pubsub │ │ └── v1 │ │ ├── pubsub.proto │ │ └── schema.proto ├── protos.d.ts ├── protos.js └── protos.json ├── renovate.json ├── samples ├── .eslintrc.yml ├── .gitignore ├── README.md ├── commitAvroSchema.js ├── commitProtoSchema.js ├── createAvroSchema.js ├── createBigQuerySubscription.js ├── createProtoSchema.js ├── createPushSubscription.js ├── createPushSubscriptionNoWrapper.js ├── createSubscription.js ├── createSubscriptionWithCloudStorage.js ├── createSubscriptionWithDeadLetterPolicy.js ├── createSubscriptionWithExactlyOnceDelivery.js ├── createSubscriptionWithFiltering.js ├── createSubscriptionWithOrdering.js ├── createSubscriptionWithRetryPolicy.js ├── createTopic.js ├── createTopicWithAwsMskIngestion.js ├── createTopicWithAzureEventHubsIngestion.js ├── createTopicWithCloudStorageIngestion.js ├── createTopicWithConfluentCloudIngestion.js ├── createTopicWithKinesisIngestion.js ├── createTopicWithSchema.js ├── createTopicWithSchemaRevisions.js ├── deleteSchema.js ├── deleteSchemaRevision.js ├── deleteSubscription.js ├── deleteTopic.js ├── detachSubscription.js ├── getSchema.js ├── getSchemaRevision.js ├── getSubscription.js ├── getSubscriptionPolicy.js ├── getTopicPolicy.js ├── listAllTopics.js ├── listSchemaRevisions.js ├── listSchemas.js ├── listSubscriptions.js ├── listTopicSubscriptions.js ├── listenForAvroRecords.js ├── listenForAvroRecordsWithRevisions.js ├── listenForErrors.js ├── listenForMessages.js ├── listenForMessagesWithExactlyOnceDelivery.js ├── listenForProtobufMessages.js ├── listenWithCustomAttributes.js ├── listenWithOpenTelemetryTracing.js ├── modifyPushConfig.js ├── optimisticSubscribe.js ├── package.json ├── publishAvroRecords.js ├── publishBatchedMessages.js ├── publishMessage.js ├── publishMessageWithCustomAttributes.js ├── publishOrderedMessage.js ├── publishProtobufMessages.js ├── publishWithFlowControl.js ├── publishWithOpenTelemetryTracing.js ├── publishWithRetrySettings.js ├── quickstart.js ├── removeDeadLetterPolicy.js ├── resumePublish.js ├── rollbackSchema.js ├── setSubscriptionPolicy.js ├── setTopicPolicy.js ├── subscribeWithFlowControlSettings.js ├── synchronousPull.js ├── synchronousPullWithDeliveryAttempts.js ├── synchronousPullWithLeaseManagement.js ├── system-test │ ├── common.test.ts │ ├── common.ts │ ├── fixtures │ │ ├── getSchema-expected.jstest │ │ ├── getSchema-expected.tstest │ │ ├── getSchema-fixture.jstest │ │ ├── getSchema-fixture.tstest │ │ ├── provinces.avsc │ │ └── provinces.proto │ ├── openTelemetryTracing.test.ts │ ├── quickstart.test.ts │ ├── schema.test.ts │ ├── subscriptions.test.ts │ ├── testResources.test.ts │ ├── testResources.ts │ └── topics.test.ts ├── testSubscriptionPermissions.js ├── testTopicPermissions.js ├── tsconfig.json ├── typescript │ ├── README.md │ ├── avro-js.d.ts │ ├── commitAvroSchema.ts │ ├── commitProtoSchema.ts │ ├── createAvroSchema.ts │ ├── createBigQuerySubscription.ts │ ├── createProtoSchema.ts │ ├── createPushSubscription.ts │ ├── createPushSubscriptionNoWrapper.ts │ ├── createSubscription.ts │ ├── createSubscriptionWithCloudStorage.ts │ ├── createSubscriptionWithDeadLetterPolicy.ts │ ├── createSubscriptionWithExactlyOnceDelivery.ts │ ├── createSubscriptionWithFiltering.ts │ ├── createSubscriptionWithOrdering.ts │ ├── createSubscriptionWithRetryPolicy.ts │ ├── createTopic.ts │ ├── createTopicWithAwsMskIngestion.ts │ ├── createTopicWithAzureEventHubsIngestion.ts │ ├── createTopicWithCloudStorageIngestion.ts │ ├── createTopicWithConfluentCloudIngestion.ts │ ├── createTopicWithKinesisIngestion.ts │ ├── createTopicWithSchema.ts │ ├── createTopicWithSchemaRevisions.ts │ ├── deleteSchema.ts │ ├── deleteSchemaRevision.ts │ ├── deleteSubscription.ts │ ├── deleteTopic.ts │ ├── detachSubscription.ts │ ├── getSchema.ts │ ├── getSchemaRevision.ts │ ├── getSubscription.ts │ ├── getSubscriptionPolicy.ts │ ├── getTopicPolicy.ts │ ├── listAllTopics.ts │ ├── listSchemaRevisions.ts │ ├── listSchemas.ts │ ├── listSubscriptions.ts │ ├── listTopicSubscriptions.ts │ ├── listenForAvroRecords.ts │ ├── listenForAvroRecordsWithRevisions.ts │ ├── listenForErrors.ts │ ├── listenForMessages.ts │ ├── listenForMessagesWithExactlyOnceDelivery.ts │ ├── listenForProtobufMessages.ts │ ├── listenWithCustomAttributes.ts │ ├── listenWithOpenTelemetryTracing.ts │ ├── modifyPushConfig.ts │ ├── optimisticSubscribe.ts │ ├── publishAvroRecords.ts │ ├── publishBatchedMessages.ts │ ├── publishMessage.ts │ ├── publishMessageWithCustomAttributes.ts │ ├── publishOrderedMessage.ts │ ├── publishProtobufMessages.ts │ ├── publishWithFlowControl.ts │ ├── publishWithOpenTelemetryTracing.ts │ ├── publishWithRetrySettings.ts │ ├── quickstart.ts │ ├── removeDeadLetterPolicy.ts │ ├── resumePublish.ts │ ├── rollbackSchema.ts │ ├── setSubscriptionPolicy.ts │ ├── setTopicPolicy.ts │ ├── subscribeWithFlowControlSettings.ts │ ├── synchronousPull.ts │ ├── synchronousPullWithDeliveryAttempts.ts │ ├── testSubscriptionPermissions.ts │ ├── testTopicPermissions.ts │ ├── tsconfig.json │ ├── updateDeadLetterPolicy.ts │ ├── updateTopicIngestionType.ts │ ├── updateTopicSchema.ts │ └── validateSchema.ts ├── updateDeadLetterPolicy.js ├── updateTopicIngestionType.js ├── updateTopicSchema.js └── validateSchema.js ├── src ├── ack-metadata.ts ├── debug.ts ├── default-options.ts ├── exponential-retry.ts ├── histogram.ts ├── iam.ts ├── index.ts ├── lease-manager.ts ├── message-queues.ts ├── message-stream.ts ├── publisher │ ├── flow-control.ts │ ├── flow-publisher.ts │ ├── index.ts │ ├── message-batch.ts │ ├── message-queues.ts │ ├── publish-error.ts │ └── pubsub-message.ts ├── pubsub.ts ├── pull-retry.ts ├── schema.ts ├── snapshot.ts ├── subscriber.ts ├── subscription.ts ├── telemetry-tracing.ts ├── temporal.ts ├── topic.ts ├── util.ts └── v1 │ ├── index.ts │ ├── publisher_client.ts │ ├── publisher_client_config.json │ ├── publisher_proto_list.json │ ├── schema_service_client.ts │ ├── schema_service_client_config.json │ ├── schema_service_proto_list.json │ ├── subscriber_client.ts │ ├── subscriber_client_config.json │ └── subscriber_proto_list.json ├── system-test ├── fixtures │ ├── ordered-messages.json │ ├── province.json │ ├── provinces.avsc │ └── sample │ │ ├── package.json │ │ ├── src │ │ └── index.ts │ │ └── tsconfig.json ├── install.ts └── pubsub.ts ├── test ├── ack-metadata.ts ├── exponential-retry.ts ├── gapic_publisher_v1.ts ├── gapic_schema_service_v1.ts ├── gapic_subscriber_v1.ts ├── histogram.ts ├── iam.ts ├── index.ts ├── lease-manager.ts ├── message-queues.ts ├── message-stream.ts ├── publisher │ ├── flow-control.ts │ ├── flow-publisher.ts │ ├── index.ts │ ├── message-batch.ts │ ├── message-queues.ts │ ├── publish-error.ts │ └── pubsub-message.ts ├── pubsub.ts ├── pull-retry.ts ├── schema.ts ├── snapshot.ts ├── subscriber.ts ├── subscription.ts ├── telemetry-tracing.ts ├── temporal.ts ├── test-utils.ts ├── topic.ts ├── tracing.ts └── util.ts ├── tsconfig.json └── webpack.config.js /.eslintignore: -------------------------------------------------------------------------------- 1 | **/node_modules 2 | **/.coverage 3 | build/ 4 | docs/ 5 | protos/ 6 | system-test/ 7 | samples/generated/ 8 | samples/typescript/ 9 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts" 3 | } 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.ts text eol=lf 2 | *.js text eol=lf 3 | protos/* linguist-generated 4 | **/api-extractor.json linguist-language=JSON-with-Comments 5 | -------------------------------------------------------------------------------- /.github/.OwlBot.lock.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 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 | # http://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 | docker: 15 | image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest 16 | digest: sha256:c7e4968cfc97a204a4b2381f3ecb55cabc40c4cccf88b1ef8bef0d976be87fee 17 | # created: 2025-04-08T17:33:08.498793944Z 18 | -------------------------------------------------------------------------------- /.github/.OwlBot.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 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 | # http://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 | docker: 15 | image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest 16 | 17 | 18 | deep-remove-regex: 19 | - /owl-bot-staging 20 | 21 | deep-copy-regex: 22 | - source: /google/pubsub/(v.*)/.*-nodejs/(.*) 23 | dest: /owl-bot-staging/$1/$2 24 | 25 | begin-after-commit-hash: 94496fa21b40a7f4d0c4881e8ed8b2bf4117e280 26 | 27 | -------------------------------------------------------------------------------- /.github/.header-checker-lint.yaml: -------------------------------------------------------------------------------- 1 | allowedCopyrightHolders: 2 | - 'Google LLC' 3 | allowedLicenses: 4 | - 'Apache-2.0' 5 | - 'MIT' 6 | - 'BSD-3' 7 | sourceFileExtensions: 8 | - 'ts' 9 | - 'js' 10 | - 'java' 11 | ignoreFiles: 12 | - 'owl-bot-staging/**' 13 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Code owners file. 2 | # This file controls who is tagged for review for any given pull request. 3 | # 4 | # For syntax help see: 5 | # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax 6 | 7 | 8 | # Unless specified, the jsteam is the default owner for nodejs repositories. 9 | * @googleapis/api-pubsub @googleapis/jsteam -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | contact_links: 2 | - name: Google Cloud Support 3 | url: https://cloud.google.com/support/ 4 | about: If you have a support contract with Google, please use the Google Cloud Support portal. 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/documentation_request.yml: -------------------------------------------------------------------------------- 1 | name: Documentation Requests 2 | description: Requests for more information 3 | body: 4 | - type: markdown 5 | attributes: 6 | value: > 7 | Please use this issue type to log documentation requests against the library itself. 8 | These requests should involve documentation on Github (`.md` files), and should relate to the library 9 | itself. If you have questions or documentation requests for an API, please 10 | reach out to the API tracker itself. 11 | 12 | Please submit an issue to the API team, either by submitting an 13 | issue in its issue tracker https://cloud.google.com/support/docs/issue-trackers), or by 14 | submitting an issue in its linked tracker in the .repo-metadata.json 15 | file in the API under packages/* ([example](https://issuetracker.google.com/savedsearches/559741)). 16 | You can also submit a request to documentation on cloud.google.com itself with the "Send Feedback" 17 | on the bottom of the page. 18 | 19 | 20 | Please note that documentation requests and questions for specific APIs 21 | will be closed. 22 | - type: checkboxes 23 | attributes: 24 | label: Please make sure you have searched for information in the following 25 | guides. 26 | options: 27 | - label: "Search the issues already opened: 28 | https://github.com/GoogleCloudPlatform/google-cloud-node/issues" 29 | required: true 30 | - label: "Check our Troubleshooting guide: 31 | https://googlecloudplatform.github.io/google-cloud-node/#/docs/guid\ 32 | es/troubleshooting" 33 | required: true 34 | - label: "Check our FAQ: 35 | https://googlecloudplatform.github.io/google-cloud-node/#/docs/guid\ 36 | es/faq" 37 | required: true 38 | - label: "Check our libraries HOW-TO: 39 | https://github.com/googleapis/gax-nodejs/blob/main/client-libraries\ 40 | .md" 41 | required: true 42 | - label: "Check out our authentication guide: 43 | https://github.com/googleapis/google-auth-library-nodejs" 44 | required: true 45 | - label: "Check out handwritten samples for many of our APIs: 46 | https://github.com/GoogleCloudPlatform/nodejs-docs-samples" 47 | required: true 48 | - type: textarea 49 | attributes: 50 | label: > 51 | Documentation Request 52 | validations: 53 | required: true 54 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: Suggest an idea for this library 3 | labels: 4 | - feature request 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: > 9 | **PLEASE READ**: If you have a support contract with Google, please 10 | create an issue in the [support 11 | console](https://cloud.google.com/support/) instead of filing on GitHub. 12 | This will ensure a timely response. Otherwise, please make sure to 13 | follow the steps below. 14 | - type: textarea 15 | attributes: 16 | label: > 17 | A screenshot that you have tested with "Try this API". 18 | description: > 19 | As our client libraries are mostly autogenerated, we kindly request 20 | that you test whether your feature request is with the client library, or with the 21 | API itself. To do so, please search for your API 22 | here: https://developers.google.com/apis-explorer and attempt to 23 | reproduce the issue in the given method. Please include a screenshot of 24 | the response in "Try this API". This response should NOT match the current 25 | behavior you are experiencing. If the behavior is the same, it means 26 | that you are likely requesting a feature for the API itself. In that 27 | case, please submit an issue to the API team, either by submitting an 28 | issue in its issue tracker https://cloud.google.com/support/docs/issue-trackers, or by 29 | submitting an issue in its linked tracker in the .repo-metadata.json 30 | file in the API under packages/* ([example](https://issuetracker.google.com/savedsearches/559741)) 31 | 32 | Example of library specific issues would be: retry strategies, authentication questions, or issues with typings. 33 | Examples of API issues would include: expanding method parameter types, adding functionality to an API. 34 | validations: 35 | required: true 36 | - type: textarea 37 | attributes: 38 | label: > 39 | What would you like to see in the library? 40 | description: > 41 | Screenshots can be provided in the issue body below. 42 | placeholder: | 43 | 1. Set up authentication like so 44 | 2. Run the program like so 45 | 3. X would be nice to happen 46 | 47 | - type: textarea 48 | attributes: 49 | label: Describe alternatives you've considered 50 | 51 | - type: textarea 52 | attributes: 53 | label: Additional context/notes -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/processs_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Process Request 3 | about: Submit a process request to the library. Process requests are any requests related to library infrastructure, for example CI/CD, publishing, releasing, broken links. 4 | --- 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/questions.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: If you have a question, please use Discussions 4 | 5 | --- 6 | 7 | If you have a general question that goes beyond the library itself, we encourage you to use [Discussions](https://github.com//discussions) 8 | to engage with fellow community members! 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/support_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Support request 3 | about: If you have a support contract with Google, please create an issue in the Google Cloud Support console. 4 | 5 | --- 6 | 7 | **PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response. 8 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly: 2 | - [ ] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/nodejs-pubsub/issues/new/choose) before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea 3 | - [ ] Ensure the tests and linter pass 4 | - [ ] Code coverage does not decrease (if any source code was changed) 5 | - [ ] Appropriate docs were updated (if necessary) 6 | 7 | Fixes # 🦕 8 | 9 | Note: If you are opening a pull request against a `legacy` branch, PLEASE BE AWARE that we generally won't accept these except for things like important security fixes, and only for a limited time. 10 | -------------------------------------------------------------------------------- /.github/auto-approve.yml: -------------------------------------------------------------------------------- 1 | processes: 2 | - "NodeDependency" -------------------------------------------------------------------------------- /.github/auto-label.yaml: -------------------------------------------------------------------------------- 1 | requestsize: 2 | enabled: true 3 | -------------------------------------------------------------------------------- /.github/generated-files-bot.yml: -------------------------------------------------------------------------------- 1 | generatedFiles: 2 | - path: '.kokoro/**' 3 | message: '`.kokoro` files are templated and should be updated in [`synthtool`](https://github.com/googleapis/synthtool)' 4 | - path: '.github/CODEOWNERS' 5 | message: 'CODEOWNERS should instead be modified via the `codeowner_team` property in .repo-metadata.json' 6 | - path: '.github/workflows/ci.yaml' 7 | message: '`.github/workflows/ci.yaml` (GitHub Actions) should be updated in [`synthtool`](https://github.com/googleapis/synthtool)' 8 | - path: '.github/generated-files-bot.+(yml|yaml)' 9 | message: '`.github/generated-files-bot.(yml|yaml)` should be updated in [`synthtool`](https://github.com/googleapis/synthtool)' 10 | - path: 'README.md' 11 | message: '`README.md` is managed by [`synthtool`](https://github.com/googleapis/synthtool). However, a partials file can be used to update the README, e.g.: https://github.com/googleapis/nodejs-storage/blob/main/.readme-partials.yaml' 12 | - path: 'samples/README.md' 13 | message: '`samples/README.md` is managed by [`synthtool`](https://github.com/googleapis/synthtool). However, a partials file can be used to update the README, e.g.: https://github.com/googleapis/nodejs-storage/blob/main/.readme-partials.yaml' 14 | ignoreAuthors: 15 | - 'gcf-owl-bot[bot]' 16 | - 'yoshi-automation' 17 | -------------------------------------------------------------------------------- /.github/release-please.yml: -------------------------------------------------------------------------------- 1 | handleGHRelease: true 2 | releaseType: node 3 | branches: 4 | - branch: legacy-v2 5 | releaseType: node 6 | handleGHRelease: true 7 | - branch: legacy-v3 8 | releaseType: node 9 | handleGHRelease: true 10 | 11 | -------------------------------------------------------------------------------- /.github/release-trigger.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | multiScmName: nodejs-pubsub -------------------------------------------------------------------------------- /.github/scripts/close-unresponsive.cjs: -------------------------------------------------------------------------------- 1 | /// Copyright 2024 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 | // http://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 | function labeledEvent(data) { 16 | return data.event === "labeled" && data.label.name === "needs more info"; 17 | } 18 | 19 | const numberOfDaysLimit = 15; 20 | const close_message = `This has been closed since a request for information has \ 21 | not been answered for ${numberOfDaysLimit} days. It can be reopened when the \ 22 | requested information is provided.`; 23 | 24 | module.exports = async ({ github, context }) => { 25 | const owner = context.repo.owner; 26 | const repo = context.repo.repo; 27 | 28 | const issues = await github.rest.issues.listForRepo({ 29 | owner: owner, 30 | repo: repo, 31 | labels: "needs more info", 32 | }); 33 | const numbers = issues.data.map((e) => e.number); 34 | 35 | for (const number of numbers) { 36 | const events = await github.paginate( 37 | github.rest.issues.listEventsForTimeline, 38 | { 39 | owner: owner, 40 | repo: repo, 41 | issue_number: number, 42 | }, 43 | (response) => response.data.filter(labeledEvent) 44 | ); 45 | 46 | const latest_response_label = events[events.length - 1]; 47 | 48 | const created_at = new Date(latest_response_label.created_at); 49 | const now = new Date(); 50 | const diff = now - created_at; 51 | const diffDays = diff / (1000 * 60 * 60 * 24); 52 | 53 | if (diffDays > numberOfDaysLimit) { 54 | await github.rest.issues.update({ 55 | owner: owner, 56 | repo: repo, 57 | issue_number: number, 58 | state: "closed", 59 | }); 60 | 61 | await github.rest.issues.createComment({ 62 | owner: owner, 63 | repo: repo, 64 | issue_number: number, 65 | body: close_message, 66 | }); 67 | } 68 | } 69 | }; -------------------------------------------------------------------------------- /.github/scripts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tests", 3 | "private": true, 4 | "description": "tests for script", 5 | "scripts": { 6 | "test": "mocha tests/close-invalid-link.test.cjs && mocha tests/close-or-remove-response-label.test.cjs" 7 | }, 8 | "author": "Google Inc.", 9 | "license": "Apache-2.0", 10 | "engines": { 11 | "node": ">=18" 12 | }, 13 | "dependencies": { 14 | "js-yaml": "^4.1.0" 15 | }, 16 | "devDependencies": { 17 | "@octokit/rest": "^21.0.0", 18 | "mocha": "^10.0.0", 19 | "sinon": "^18.0.0" 20 | } 21 | } -------------------------------------------------------------------------------- /.github/scripts/remove-response-label.cjs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | module.exports = async ({ github, context }) => { 16 | const commenter = context.actor; 17 | const issue = await github.rest.issues.get({ 18 | owner: context.repo.owner, 19 | repo: context.repo.repo, 20 | issue_number: context.issue.number, 21 | }); 22 | const author = issue.data.user.login; 23 | const labels = issue.data.labels.map((e) => e.name); 24 | 25 | if (author === commenter && labels.includes("needs more info")) { 26 | await github.rest.issues.removeLabel({ 27 | owner: context.repo.owner, 28 | repo: context.repo.repo, 29 | issue_number: context.issue.number, 30 | name: "needs more info", 31 | }); 32 | } 33 | }; -------------------------------------------------------------------------------- /.github/sync-repo-settings.yaml: -------------------------------------------------------------------------------- 1 | branchProtectionRules: 2 | - pattern: main 3 | isAdminEnforced: true 4 | requiredApprovingReviewCount: 1 5 | requiresCodeOwnerReviews: true 6 | requiresStrictStatusChecks: true 7 | requiredStatusCheckContexts: 8 | - "ci/kokoro: Samples test" 9 | - "ci/kokoro: System test" 10 | - lint 11 | - test (18) 12 | - test (20) 13 | - test (22) 14 | - cla/google 15 | - windows 16 | - OwlBot Post Processor 17 | permissionRules: 18 | - team: yoshi-admins 19 | permission: admin 20 | - team: jsteam-admins 21 | permission: admin 22 | - team: jsteam 23 | permission: push 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | pull_request: 6 | name: ci 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | node: [18, 20, 22] 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: actions/setup-node@v4 16 | with: 17 | node-version: ${{ matrix.node }} 18 | - run: node --version 19 | # The first installation step ensures that all of our production 20 | # dependencies work on the given Node.js version, this helps us find 21 | # dependencies that don't match our engines field: 22 | - run: npm install --production --engine-strict --ignore-scripts --no-package-lock 23 | # Clean up the production install, before installing dev/production: 24 | - run: rm -rf node_modules 25 | - run: npm install --engine-strict 26 | - run: npm test 27 | env: 28 | MOCHA_THROW_DEPRECATION: false 29 | test-script: 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: actions/checkout@v4 33 | - uses: actions/setup-node@v4 34 | with: 35 | node-version: 18 36 | - run: node --version 37 | - run: npm install --engine-strict 38 | working-directory: .github/scripts 39 | - run: npm test 40 | working-directory: .github/scripts 41 | env: 42 | MOCHA_THROW_DEPRECATION: false 43 | windows: 44 | runs-on: windows-latest 45 | steps: 46 | - uses: actions/checkout@v4 47 | - uses: actions/setup-node@v4 48 | with: 49 | node-version: 18 50 | - run: npm install --engine-strict 51 | - run: npm test 52 | env: 53 | MOCHA_THROW_DEPRECATION: false 54 | lint: 55 | runs-on: ubuntu-latest 56 | steps: 57 | - uses: actions/checkout@v4 58 | - uses: actions/setup-node@v4 59 | with: 60 | node-version: 18 61 | - run: npm install 62 | - run: npm run lint 63 | docs: 64 | runs-on: ubuntu-latest 65 | steps: 66 | - uses: actions/checkout@v4 67 | - uses: actions/setup-node@v4 68 | with: 69 | node-version: 18 70 | - run: npm install 71 | - run: npm run docs 72 | - uses: JustinBeckwith/linkinator-action@v1 73 | with: 74 | paths: docs/ 75 | -------------------------------------------------------------------------------- /.github/workflows/issues-no-repro.yaml: -------------------------------------------------------------------------------- 1 | name: invalid_link 2 | on: 3 | issues: 4 | types: [opened, reopened] 5 | 6 | jobs: 7 | close: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | issues: write 11 | pull-requests: write 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions/setup-node@v3 15 | with: 16 | node-version: 18 17 | - run: npm install 18 | working-directory: ./.github/scripts 19 | - uses: actions/github-script@v7 20 | with: 21 | script: | 22 | const script = require('./.github/scripts/close-invalid-link.cjs') 23 | await script({github, context}) 24 | -------------------------------------------------------------------------------- /.github/workflows/response.yaml: -------------------------------------------------------------------------------- 1 | name: no_response 2 | on: 3 | schedule: 4 | - cron: '30 1 * * *' # Run every day at 01:30 5 | workflow_dispatch: 6 | issue_comment: 7 | 8 | jobs: 9 | close: 10 | if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' 11 | runs-on: ubuntu-latest 12 | permissions: 13 | issues: write 14 | pull-requests: write 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/github-script@v7 18 | with: 19 | script: | 20 | const script = require('./.github/scripts/close-unresponsive.cjs') 21 | await script({github, context}) 22 | 23 | remove_label: 24 | if: github.event_name == 'issue_comment' 25 | runs-on: ubuntu-latest 26 | permissions: 27 | issues: write 28 | pull-requests: write 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: actions/github-script@v7 32 | with: 33 | script: | 34 | const script = require('./.github/scripts/remove-response-label.cjs') 35 | await script({github, context}) 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/*.log 2 | **/node_modules 3 | /.coverage 4 | /coverage 5 | /.nyc_output 6 | /docs/ 7 | /out/ 8 | /build/ 9 | system-test/secrets.js 10 | system-test/*key.json 11 | *.lock 12 | .DS_Store 13 | package-lock.json 14 | __pycache__ 15 | -------------------------------------------------------------------------------- /.jsdoc.js: -------------------------------------------------------------------------------- 1 | // Copyright 2025 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 | // ** This file is automatically generated by gapic-generator-typescript. ** 16 | // ** https://github.com/googleapis/gapic-generator-typescript ** 17 | // ** All changes to this file may be overwritten. ** 18 | 19 | 'use strict'; 20 | 21 | module.exports = { 22 | opts: { 23 | readme: './README.md', 24 | package: './package.json', 25 | template: './node_modules/jsdoc-fresh', 26 | recurse: true, 27 | verbose: true, 28 | destination: './docs/' 29 | }, 30 | plugins: [ 31 | 'plugins/markdown', 32 | 'jsdoc-region-tag' 33 | ], 34 | source: { 35 | excludePattern: '(^|\\/|\\\\)[._]', 36 | include: [ 37 | 'build/src', 38 | 'protos' 39 | ], 40 | includePattern: '\\.js$' 41 | }, 42 | templates: { 43 | copyright: 'Copyright 2025 Google LLC', 44 | includeDate: false, 45 | sourceFiles: false, 46 | systemName: '@google-cloud/pubsub', 47 | theme: 'lumen', 48 | default: { 49 | outputSourceFiles: false 50 | } 51 | }, 52 | markdown: { 53 | idInHeadings: true 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /.kokoro/.gitattributes: -------------------------------------------------------------------------------- 1 | * linguist-generated=true 2 | -------------------------------------------------------------------------------- /.kokoro/common.cfg: -------------------------------------------------------------------------------- 1 | # Format: //devtools/kokoro/config/proto/build.proto 2 | 3 | # Build logs will be here 4 | action { 5 | define_artifacts { 6 | regex: "**/*sponge_log.xml" 7 | } 8 | } 9 | 10 | # Download trampoline resources. 11 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" 12 | 13 | # Use the trampoline script to run in docker. 14 | build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" 15 | 16 | # Configure the docker image for kokoro-trampoline. 17 | env_vars: { 18 | key: "TRAMPOLINE_IMAGE" 19 | value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" 20 | } 21 | env_vars: { 22 | key: "TRAMPOLINE_BUILD_FILE" 23 | value: "github/nodejs-pubsub/.kokoro/test.sh" 24 | } 25 | -------------------------------------------------------------------------------- /.kokoro/continuous/node18/common.cfg: -------------------------------------------------------------------------------- 1 | # Format: //devtools/kokoro/config/proto/build.proto 2 | 3 | # Build logs will be here 4 | action { 5 | define_artifacts { 6 | regex: "**/*sponge_log.xml" 7 | } 8 | } 9 | 10 | # Download trampoline resources. 11 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" 12 | 13 | # Use the trampoline script to run in docker. 14 | build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" 15 | 16 | # Configure the docker image for kokoro-trampoline. 17 | env_vars: { 18 | key: "TRAMPOLINE_IMAGE" 19 | value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" 20 | } 21 | env_vars: { 22 | key: "TRAMPOLINE_BUILD_FILE" 23 | value: "github/nodejs-pubsub/.kokoro/test.sh" 24 | } 25 | -------------------------------------------------------------------------------- /.kokoro/continuous/node18/lint.cfg: -------------------------------------------------------------------------------- 1 | env_vars: { 2 | key: "TRAMPOLINE_BUILD_FILE" 3 | value: "github/nodejs-pubsub/.kokoro/lint.sh" 4 | } 5 | -------------------------------------------------------------------------------- /.kokoro/continuous/node18/samples-test.cfg: -------------------------------------------------------------------------------- 1 | # Download resources for system tests (service account key, etc.) 2 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" 3 | 4 | env_vars: { 5 | key: "TRAMPOLINE_BUILD_FILE" 6 | value: "github/nodejs-pubsub/.kokoro/samples-test.sh" 7 | } 8 | 9 | env_vars: { 10 | key: "SECRET_MANAGER_KEYS" 11 | value: "long-door-651-kokoro-system-test-service-account" 12 | } -------------------------------------------------------------------------------- /.kokoro/continuous/node18/system-test.cfg: -------------------------------------------------------------------------------- 1 | # Download resources for system tests (service account key, etc.) 2 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" 3 | 4 | env_vars: { 5 | key: "TRAMPOLINE_BUILD_FILE" 6 | value: "github/nodejs-pubsub/.kokoro/system-test.sh" 7 | } 8 | 9 | env_vars: { 10 | key: "SECRET_MANAGER_KEYS" 11 | value: "long-door-651-kokoro-system-test-service-account" 12 | } -------------------------------------------------------------------------------- /.kokoro/continuous/node18/test.cfg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googleapis/nodejs-pubsub/62e73b885a192d48a61cc945cf36c3920250b0bf/.kokoro/continuous/node18/test.cfg -------------------------------------------------------------------------------- /.kokoro/docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2018 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 20 | 21 | cd $(dirname $0)/.. 22 | 23 | npm install 24 | 25 | npm run docs-test 26 | -------------------------------------------------------------------------------- /.kokoro/lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2018 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 20 | 21 | cd $(dirname $0)/.. 22 | 23 | npm install 24 | 25 | # Install and link samples 26 | if [ -f samples/package.json ]; then 27 | cd samples/ 28 | npm link ../ 29 | npm install 30 | cd .. 31 | fi 32 | 33 | npm run lint 34 | -------------------------------------------------------------------------------- /.kokoro/presubmit/node18/common.cfg: -------------------------------------------------------------------------------- 1 | # Format: //devtools/kokoro/config/proto/build.proto 2 | 3 | # Build logs will be here 4 | action { 5 | define_artifacts { 6 | regex: "**/*sponge_log.xml" 7 | } 8 | } 9 | 10 | # Download trampoline resources. 11 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" 12 | 13 | # Use the trampoline script to run in docker. 14 | build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" 15 | 16 | # Configure the docker image for kokoro-trampoline. 17 | env_vars: { 18 | key: "TRAMPOLINE_IMAGE" 19 | value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" 20 | } 21 | env_vars: { 22 | key: "TRAMPOLINE_BUILD_FILE" 23 | value: "github/nodejs-pubsub/.kokoro/test.sh" 24 | } 25 | -------------------------------------------------------------------------------- /.kokoro/presubmit/node18/samples-test.cfg: -------------------------------------------------------------------------------- 1 | # Download resources for system tests (service account key, etc.) 2 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" 3 | 4 | env_vars: { 5 | key: "TRAMPOLINE_BUILD_FILE" 6 | value: "github/nodejs-pubsub/.kokoro/samples-test.sh" 7 | } 8 | 9 | env_vars: { 10 | key: "SECRET_MANAGER_KEYS" 11 | value: "long-door-651-kokoro-system-test-service-account" 12 | } -------------------------------------------------------------------------------- /.kokoro/presubmit/node18/system-test.cfg: -------------------------------------------------------------------------------- 1 | # Download resources for system tests (service account key, etc.) 2 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" 3 | 4 | env_vars: { 5 | key: "TRAMPOLINE_BUILD_FILE" 6 | value: "github/nodejs-pubsub/.kokoro/system-test.sh" 7 | } 8 | 9 | env_vars: { 10 | key: "SECRET_MANAGER_KEYS" 11 | value: "long-door-651-kokoro-system-test-service-account" 12 | } -------------------------------------------------------------------------------- /.kokoro/presubmit/node18/test.cfg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googleapis/nodejs-pubsub/62e73b885a192d48a61cc945cf36c3920250b0bf/.kokoro/presubmit/node18/test.cfg -------------------------------------------------------------------------------- /.kokoro/presubmit/windows/common.cfg: -------------------------------------------------------------------------------- 1 | # Format: //devtools/kokoro/config/proto/build.proto 2 | 3 | -------------------------------------------------------------------------------- /.kokoro/presubmit/windows/test.cfg: -------------------------------------------------------------------------------- 1 | # Use the test file directly 2 | build_file: "nodejs-pubsub/.kokoro/test.bat" 3 | -------------------------------------------------------------------------------- /.kokoro/publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2018 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 20 | 21 | # Start the releasetool reporter 22 | python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script 23 | 24 | cd $(dirname $0)/.. 25 | 26 | NPM_TOKEN=$(cat $KOKORO_KEYSTORE_DIR/73713_google-cloud-npm-token-1) 27 | echo "//wombat-dressing-room.appspot.com/:_authToken=${NPM_TOKEN}" > ~/.npmrc 28 | 29 | npm install 30 | npm pack . 31 | # npm provides no way to specify, observe, or predict the name of the tarball 32 | # file it generates. We have to look in the current directory for the freshest 33 | # .tgz file. 34 | TARBALL=$(ls -1 -t *.tgz | head -1) 35 | 36 | npm publish --access=public --registry=https://wombat-dressing-room.appspot.com "$TARBALL" 37 | 38 | # Kokoro collects *.tgz and package-lock.json files and stores them in Placer 39 | # so we can generate SBOMs and attestations. 40 | # However, we *don't* want Kokoro to collect package-lock.json and *.tgz files 41 | # that happened to be installed with dependencies. 42 | find node_modules -name package-lock.json -o -name "*.tgz" | xargs rm -f -------------------------------------------------------------------------------- /.kokoro/release/common.cfg: -------------------------------------------------------------------------------- 1 | before_action { 2 | fetch_keystore { 3 | keystore_resource { 4 | keystore_config_id: 73713 5 | keyname: "yoshi-automation-github-key" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.kokoro/release/docs-devsite.cfg: -------------------------------------------------------------------------------- 1 | # service account used to publish up-to-date docs. 2 | before_action { 3 | fetch_keystore { 4 | keystore_resource { 5 | keystore_config_id: 73713 6 | keyname: "docuploader_service_account" 7 | } 8 | } 9 | } 10 | 11 | # doc publications use a Python image. 12 | env_vars: { 13 | key: "TRAMPOLINE_IMAGE" 14 | value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" 15 | } 16 | 17 | # Download trampoline resources. 18 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" 19 | 20 | # Use the trampoline script to run in docker. 21 | build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" 22 | 23 | env_vars: { 24 | key: "TRAMPOLINE_BUILD_FILE" 25 | value: "github/nodejs-pubsub/.kokoro/release/docs-devsite.sh" 26 | } 27 | -------------------------------------------------------------------------------- /.kokoro/release/docs-devsite.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2021 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | if [[ -z "$CREDENTIALS" ]]; then 20 | # if CREDENTIALS are explicitly set, assume we're testing locally 21 | # and don't set NPM_CONFIG_PREFIX. 22 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 23 | export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" 24 | cd $(dirname $0)/../.. 25 | fi 26 | 27 | npm install 28 | npm install --no-save @google-cloud/cloud-rad@^0.4.0 29 | # publish docs to devsite 30 | npx @google-cloud/cloud-rad . cloud-rad 31 | -------------------------------------------------------------------------------- /.kokoro/release/docs.cfg: -------------------------------------------------------------------------------- 1 | # service account used to publish up-to-date docs. 2 | before_action { 3 | fetch_keystore { 4 | keystore_resource { 5 | keystore_config_id: 73713 6 | keyname: "docuploader_service_account" 7 | } 8 | } 9 | } 10 | 11 | # doc publications use a Python image. 12 | env_vars: { 13 | key: "TRAMPOLINE_IMAGE" 14 | value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" 15 | } 16 | 17 | # Download trampoline resources. 18 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" 19 | 20 | # Use the trampoline script to run in docker. 21 | build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" 22 | 23 | env_vars: { 24 | key: "TRAMPOLINE_BUILD_FILE" 25 | value: "github/nodejs-pubsub/.kokoro/release/docs.sh" 26 | } 27 | -------------------------------------------------------------------------------- /.kokoro/release/docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2019 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | # build jsdocs (Python is installed on the Node 18 docker image). 20 | if [[ -z "$CREDENTIALS" ]]; then 21 | # if CREDENTIALS are explicitly set, assume we're testing locally 22 | # and don't set NPM_CONFIG_PREFIX. 23 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 24 | export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" 25 | cd $(dirname $0)/../.. 26 | fi 27 | npm install 28 | npm run docs 29 | 30 | # create docs.metadata, based on package.json and .repo-metadata.json. 31 | npm i json@9.0.6 -g 32 | python3 -m docuploader create-metadata \ 33 | --name=$(cat .repo-metadata.json | json name) \ 34 | --version=$(cat package.json | json version) \ 35 | --language=$(cat .repo-metadata.json | json language) \ 36 | --distribution-name=$(cat .repo-metadata.json | json distribution_name) \ 37 | --product-page=$(cat .repo-metadata.json | json product_documentation) \ 38 | --github-repository=$(cat .repo-metadata.json | json repo) \ 39 | --issue-tracker=$(cat .repo-metadata.json | json issue_tracker) 40 | cp docs.metadata ./docs/docs.metadata 41 | 42 | # deploy the docs. 43 | if [[ -z "$CREDENTIALS" ]]; then 44 | CREDENTIALS=${KOKORO_KEYSTORE_DIR}/73713_docuploader_service_account 45 | fi 46 | if [[ -z "$BUCKET" ]]; then 47 | BUCKET=docs-staging 48 | fi 49 | python3 -m docuploader upload ./docs --credentials $CREDENTIALS --staging-bucket $BUCKET 50 | -------------------------------------------------------------------------------- /.kokoro/release/publish.cfg: -------------------------------------------------------------------------------- 1 | before_action { 2 | fetch_keystore { 3 | keystore_resource { 4 | keystore_config_id: 73713 5 | keyname: "docuploader_service_account" 6 | } 7 | } 8 | } 9 | 10 | before_action { 11 | fetch_keystore { 12 | keystore_resource { 13 | keystore_config_id: 73713 14 | keyname: "google-cloud-npm-token-1" 15 | } 16 | } 17 | } 18 | 19 | env_vars: { 20 | key: "SECRET_MANAGER_KEYS" 21 | value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" 22 | } 23 | 24 | # Download trampoline resources. 25 | gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" 26 | 27 | # Use the trampoline script to run in docker. 28 | build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" 29 | 30 | # Configure the docker image for kokoro-trampoline. 31 | env_vars: { 32 | key: "TRAMPOLINE_IMAGE" 33 | value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" 34 | } 35 | 36 | env_vars: { 37 | key: "TRAMPOLINE_BUILD_FILE" 38 | value: "github/nodejs-pubsub/.kokoro/publish.sh" 39 | } 40 | 41 | # Store the packages we uploaded to npmjs.org and their corresponding 42 | # package-lock.jsons in Placer. That way, we have a record of exactly 43 | # what we published, and which version of which tools we used to publish 44 | # it, which we can use to generate SBOMs and attestations. 45 | action { 46 | define_artifacts { 47 | regex: "github/**/*.tgz" 48 | regex: "github/**/package-lock.json" 49 | strip_prefix: "github" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /.kokoro/samples-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2018 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | # Ensure the npm global directory is writable, otherwise rebuild `npm` 20 | mkdir -p $NPM_CONFIG_PREFIX 21 | npm config -g ls || npm i -g npm@`npm --version` 22 | 23 | # Setup service account credentials. 24 | export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/long-door-651-kokoro-system-test-service-account 25 | export GCLOUD_PROJECT=long-door-651 26 | 27 | cd $(dirname $0)/.. 28 | 29 | # Run a pre-test hook, if a pre-samples-test.sh is in the project 30 | if [ -f .kokoro/pre-samples-test.sh ]; then 31 | set +x 32 | . .kokoro/pre-samples-test.sh 33 | set -x 34 | fi 35 | 36 | if [ -f samples/package.json ]; then 37 | npm install 38 | 39 | # Install and link samples 40 | cd samples/ 41 | npm link ../ 42 | npm install 43 | cd .. 44 | # If tests are running against main branch, configure flakybot 45 | # to open issues on failures: 46 | if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then 47 | export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml 48 | export MOCHA_REPORTER=xunit 49 | cleanup() { 50 | chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot 51 | $KOKORO_GFILE_DIR/linux_amd64/flakybot 52 | } 53 | trap cleanup EXIT HUP 54 | fi 55 | 56 | npm run samples-test 57 | fi 58 | 59 | # codecov combines coverage across integration and unit tests. Include 60 | # the logic below for any environment you wish to collect coverage for: 61 | COVERAGE_NODE=18 62 | if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then 63 | NYC_BIN=./node_modules/nyc/bin/nyc.js 64 | if [ -f "$NYC_BIN" ]; then 65 | $NYC_BIN report || true 66 | fi 67 | bash $KOKORO_GFILE_DIR/codecov.sh 68 | else 69 | echo "coverage is only reported for Node $COVERAGE_NODE" 70 | fi 71 | -------------------------------------------------------------------------------- /.kokoro/system-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2018 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 20 | 21 | # Setup service account credentials. 22 | export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/long-door-651-kokoro-system-test-service-account 23 | export GCLOUD_PROJECT=long-door-651 24 | 25 | cd $(dirname $0)/.. 26 | 27 | # Run a pre-test hook, if a pre-system-test.sh is in the project 28 | if [ -f .kokoro/pre-system-test.sh ]; then 29 | set +x 30 | . .kokoro/pre-system-test.sh 31 | set -x 32 | fi 33 | 34 | npm install 35 | 36 | # If tests are running against main branch, configure flakybot 37 | # to open issues on failures: 38 | if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then 39 | export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml 40 | export MOCHA_REPORTER=xunit 41 | cleanup() { 42 | chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot 43 | $KOKORO_GFILE_DIR/linux_amd64/flakybot 44 | } 45 | trap cleanup EXIT HUP 46 | fi 47 | 48 | npm run system-test 49 | 50 | # codecov combines coverage across integration and unit tests. Include 51 | # the logic below for any environment you wish to collect coverage for: 52 | COVERAGE_NODE=18 53 | if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then 54 | NYC_BIN=./node_modules/nyc/bin/nyc.js 55 | if [ -f "$NYC_BIN" ]; then 56 | $NYC_BIN report || true 57 | fi 58 | bash $KOKORO_GFILE_DIR/codecov.sh 59 | else 60 | echo "coverage is only reported for Node $COVERAGE_NODE" 61 | fi 62 | -------------------------------------------------------------------------------- /.kokoro/test.bat: -------------------------------------------------------------------------------- 1 | @rem Copyright 2018 Google LLC. All rights reserved. 2 | @rem 3 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 4 | @rem you may not use this file except in compliance with the License. 5 | @rem You may obtain a copy of the License at 6 | @rem 7 | @rem http://www.apache.org/licenses/LICENSE-2.0 8 | @rem 9 | @rem Unless required by applicable law or agreed to in writing, software 10 | @rem distributed under the License is distributed on an "AS IS" BASIS, 11 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | @rem See the License for the specific language governing permissions and 13 | @rem limitations under the License. 14 | 15 | @echo "Starting Windows build" 16 | 17 | cd /d %~dp0 18 | cd .. 19 | 20 | @rem npm path is not currently set in our image, we should fix this next time 21 | @rem we upgrade Node.js in the image: 22 | SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm 23 | 24 | call nvm use 18 25 | call which node 26 | 27 | call npm install || goto :error 28 | call npm run test || goto :error 29 | 30 | goto :EOF 31 | 32 | :error 33 | exit /b 1 34 | -------------------------------------------------------------------------------- /.kokoro/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2018 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | set -eo pipefail 18 | 19 | export NPM_CONFIG_PREFIX=${HOME}/.npm-global 20 | 21 | cd $(dirname $0)/.. 22 | 23 | npm install 24 | # If tests are running against main branch, configure flakybot 25 | # to open issues on failures: 26 | if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then 27 | export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml 28 | export MOCHA_REPORTER=xunit 29 | cleanup() { 30 | chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot 31 | $KOKORO_GFILE_DIR/linux_amd64/flakybot 32 | } 33 | trap cleanup EXIT HUP 34 | fi 35 | # Unit tests exercise the entire API surface, which may include 36 | # deprecation warnings: 37 | export MOCHA_THROW_DEPRECATION=false 38 | npm test 39 | 40 | # codecov combines coverage across integration and unit tests. Include 41 | # the logic below for any environment you wish to collect coverage for: 42 | COVERAGE_NODE=18 43 | if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then 44 | NYC_BIN=./node_modules/nyc/bin/nyc.js 45 | if [ -f "$NYC_BIN" ]; then 46 | $NYC_BIN report || true 47 | fi 48 | bash $KOKORO_GFILE_DIR/codecov.sh 49 | else 50 | echo "coverage is only reported for Node $COVERAGE_NODE" 51 | fi 52 | -------------------------------------------------------------------------------- /.kokoro/trampoline.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2017 Google Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | # This file is not used any more, but we keep this file for making it 17 | # easy to roll back. 18 | # TODO: Remove this file from the template. 19 | 20 | set -eo pipefail 21 | 22 | # Always run the cleanup script, regardless of the success of bouncing into 23 | # the container. 24 | function cleanup() { 25 | chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh 26 | ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh 27 | echo "cleanup"; 28 | } 29 | trap cleanup EXIT 30 | 31 | $(dirname $0)/populate-secrets.sh # Secret Manager secrets. 32 | python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" 33 | -------------------------------------------------------------------------------- /.mocharc.js: -------------------------------------------------------------------------------- 1 | // Copyright 2020 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 | // http://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 | const config = { 15 | "enable-source-maps": true, 16 | "throw-deprecation": true, 17 | "timeout": 10000, 18 | "recursive": true 19 | } 20 | if (process.env.MOCHA_THROW_DEPRECATION === 'false') { 21 | delete config['throw-deprecation']; 22 | } 23 | if (process.env.MOCHA_REPORTER) { 24 | config.reporter = process.env.MOCHA_REPORTER; 25 | } 26 | if (process.env.MOCHA_REPORTER_OUTPUT) { 27 | config['reporter-option'] = `output=${process.env.MOCHA_REPORTER_OUTPUT}`; 28 | } 29 | module.exports = config 30 | -------------------------------------------------------------------------------- /.mocharc.json: -------------------------------------------------------------------------------- 1 | { 2 | "enable-source-maps": true, 3 | "throw-deprecation": true, 4 | "timeout": 10000 5 | } 6 | -------------------------------------------------------------------------------- /.nycrc: -------------------------------------------------------------------------------- 1 | { 2 | "report-dir": "./.coverage", 3 | "reporter": ["text", "lcov"], 4 | "exclude": [ 5 | "**/*-test", 6 | "**/.coverage", 7 | "**/apis", 8 | "**/benchmark", 9 | "**/conformance", 10 | "**/docs", 11 | "**/samples", 12 | "**/scripts", 13 | "**/protos", 14 | "**/test", 15 | "**/*.d.ts", 16 | ".jsdoc.js", 17 | "**/.jsdoc.js", 18 | "karma.conf.js", 19 | "webpack-tests.config.js", 20 | "webpack.config.js" 21 | ], 22 | "exclude-after-remap": false, 23 | "all": true 24 | } 25 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | **/node_modules 2 | **/coverage 3 | test/fixtures 4 | build/ 5 | docs/ 6 | protos/ 7 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | // Copyright 2020 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 | module.exports = { 16 | ...require('gts/.prettierrc.json') 17 | } 18 | -------------------------------------------------------------------------------- /.readme-partials.yml: -------------------------------------------------------------------------------- 1 | introduction: |- 2 | [Cloud Pub/Sub](https://cloud.google.com/pubsub/docs) is a fully-managed real-time messaging service that allows 3 | you to send and receive messages between independent applications. 4 | 5 | This document contains links to an [API reference](https://cloud.google.com/nodejs/docs/reference/pubsub/latest/overview), samples, 6 | and other resources useful to developing Node.js applications. 7 | For additional help developing Pub/Sub applications, in Node.js and other languages, see our 8 | [Pub/Sub quickstart](https://cloud.google.com/pubsub/docs/quickstart-client-libraries), 9 | [publisher](https://cloud.google.com/pubsub/docs/publisher), and [subscriber](https://cloud.google.com/pubsub/docs/subscriber) 10 | guides. 11 | body: |- 12 | ## Running gRPC C++ bindings 13 | 14 | For some workflows and environments it might make sense to use the C++ gRPC implementation, 15 | instead of the default one (see: [#770](https://github.com/googleapis/nodejs-pubsub/issues/770)): 16 | 17 | To configure `@google-cloud/pubsub` to use an alternative `grpc` transport: 18 | 19 | 1. `npm install grpc`, adding `grpc` as a dependency. 20 | 1. instantiate `@google-cloud/pubsub` with `grpc`: 21 | 22 | ```js 23 | const {PubSub} = require('@google-cloud/pubsub'); 24 | const grpc = require('grpc'); 25 | const pubsub = new PubSub({grpc}); 26 | ``` 27 | -------------------------------------------------------------------------------- /.repo-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "distribution_name": "@google-cloud/pubsub", 3 | "release_level": "stable", 4 | "product_documentation": "https://cloud.google.com/pubsub/docs/", 5 | "repo": "googleapis/nodejs-pubsub", 6 | "default_version": "v1", 7 | "language": "nodejs", 8 | "requires_billing": true, 9 | "issue_tracker": "https://issuetracker.google.com/savedsearches/559741", 10 | "client_documentation": "https://cloud.google.com/nodejs/docs/reference/pubsub/latest", 11 | "name": "pubsub", 12 | "name_pretty": "Google Cloud Pub/Sub", 13 | "api_id": "pubsub.googleapis.com", 14 | "codeowner_team": "@googleapis/api-pubsub", 15 | "api_shortname": "pubsub", 16 | "library_type": "GAPIC_COMBO" 17 | } 18 | -------------------------------------------------------------------------------- /.trampolinerc: -------------------------------------------------------------------------------- 1 | # Copyright 2020 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 | # http://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 | # Template for .trampolinerc 16 | 17 | # Add required env vars here. 18 | required_envvars+=( 19 | ) 20 | 21 | # Add env vars which are passed down into the container here. 22 | pass_down_envvars+=( 23 | "AUTORELEASE_PR" 24 | "VERSION" 25 | ) 26 | 27 | # Prevent unintentional override on the default image. 28 | if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ 29 | [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then 30 | echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." 31 | exit 1 32 | fi 33 | 34 | # Define the default value if it makes sense. 35 | if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then 36 | TRAMPOLINE_IMAGE_UPLOAD="" 37 | fi 38 | 39 | if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then 40 | TRAMPOLINE_IMAGE="" 41 | fi 42 | 43 | if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then 44 | TRAMPOLINE_DOCKERFILE="" 45 | fi 46 | 47 | if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then 48 | TRAMPOLINE_BUILD_FILE="" 49 | fi 50 | 51 | # Secret Manager secrets. 52 | source ${PROJECT_ROOT}/.kokoro/populate-secrets.sh 53 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). 4 | 5 | The Google Security Team will respond within 5 working days of your report on g.co/vulnz. 6 | 7 | We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. 8 | -------------------------------------------------------------------------------- /bin/README.md: -------------------------------------------------------------------------------- 1 | # benchwrapper 2 | 3 | benchwrapper is a lightweight gRPC server that wraps the pubsub library for 4 | bencharmking purposes. 5 | 6 | ## Running 7 | 8 | ``` 9 | cd nodejs-pubsub 10 | npm install 11 | export PUBSUB_EMULATOR_HOST=localhost:8080 12 | npm run benchwrapper -- --port 50051 13 | ``` 14 | -------------------------------------------------------------------------------- /bin/benchwrapper.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | // http://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 | const {grpc} = require('google-gax'); 16 | const protoLoader = require('@grpc/proto-loader'); 17 | const {PubSub} = require('../build/src'); 18 | 19 | const argv = require('yargs') 20 | .option('port', { 21 | description: 'The port that the Node.js benchwrapper should run on.', 22 | type: 'number', 23 | demand: true, 24 | }) 25 | .parse(); 26 | 27 | const PROTO_PATH = __dirname + '/pubsub.proto'; 28 | // Suggested options for similarity to existing grpc.load behavior. 29 | const packageDefinition = protoLoader.loadSync(PROTO_PATH, { 30 | keepCase: true, 31 | longs: String, 32 | enums: String, 33 | defaults: true, 34 | oneofs: true, 35 | }); 36 | const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); 37 | const pubsubBenchWrapper = protoDescriptor.pubsub_bench; 38 | 39 | const client = new PubSub(); 40 | 41 | function recv(call, callback) { 42 | const subName = call.request.sub_name; 43 | 44 | const sub = client.subscription(subName); 45 | 46 | sub.setOptions({ 47 | streamingOptions: { 48 | maxStreams: 1, 49 | }, 50 | }); 51 | 52 | sub.on('message', message => { 53 | message.ack(); 54 | }); 55 | 56 | sub.on('error', () => { 57 | // We look for an error here since we expect the server 58 | // the close the stream with an grpc "OK" error, which 59 | // indicates a successfully closed stream. 60 | callback(null, null); 61 | }); 62 | } 63 | 64 | const server = new grpc.Server(); 65 | 66 | server.addService(pubsubBenchWrapper['PubsubBenchWrapper']['service'], { 67 | Recv: recv, 68 | }); 69 | console.log(`starting on localhost:${argv.port}`); 70 | server.bindAsync( 71 | `0.0.0.0:${argv.port}`, 72 | grpc.ServerCredentials.createInsecure(), 73 | err => { 74 | if (err) { 75 | throw err; 76 | } else { 77 | server.start(); 78 | } 79 | }, 80 | ); 81 | -------------------------------------------------------------------------------- /bin/pubsub.proto: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | // http://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 | syntax = "proto3"; 16 | 17 | package pubsub_bench; 18 | 19 | option java_multiple_files = true; 20 | 21 | message PubsubRecv { 22 | // The subscription identifier corresponding to number of messages sent. 23 | string sub_name = 1; 24 | } 25 | 26 | // TODO(deklerk): Replace with Google's canonical Empty. 27 | message EmptyResponse {} 28 | 29 | service PubsubBenchWrapper { 30 | // Recv represents opening a streaming pull stream to receive messages on. 31 | rpc Recv(PubsubRecv) returns (EmptyResponse) {} 32 | } 33 | -------------------------------------------------------------------------------- /helperMethods.ts.tmpl: -------------------------------------------------------------------------------- 1 | /** 2 | * This part will be added into src/v1/key_management_service_client.ts by synth.py. 3 | * KMS service requires IAM client for [setIamPolicy, getIamPolicy, testIamPerssion] methods. 4 | * But we don't support it now in micro-generators for rerouting one service to another and mix them in. 5 | * New feature request link: [https://github.com/googleapis/gapic-generator-typescript/issues/315] 6 | * 7 | * So this is manually written for providing methods to the KMS client. 8 | * IamClient is created for KMS client in the constructor using src/helper.ts. 9 | * [setIamPolicy, getIamPolicy, testIamPerssion] methods are created which is calling the corresponding methods from IamClient in `helper.ts`. 10 | */ 11 | 12 | getIamPolicy( 13 | request: protos.google.iam.v1.GetIamPolicyRequest, 14 | options: gax.CallOptions, 15 | callback: protos.google.iam.v1.IAMPolicy.GetIamPolicyCallback 16 | ) { 17 | return this._iamClient.getIamPolicy(request, options, callback); 18 | } 19 | setIamPolicy( 20 | request: protos.google.iam.v1.SetIamPolicyRequest, 21 | options: gax.CallOptions, 22 | callback: protos.google.iam.v1.IAMPolicy.SetIamPolicyCallback 23 | ) { 24 | return this._iamClient.setIamPolicy(request, options, callback); 25 | } 26 | testIamPermissions( 27 | request: protos.google.iam.v1.TestIamPermissionsRequest, 28 | options: gax.CallOptions, 29 | callback?: protos.google.iam.v1.IAMPolicy.TestIamPermissionsCallback 30 | ) { 31 | return this._iamClient.testIamPermissions(request, options, callback); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /linkinator.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "recurse": true, 3 | "skip": [ 4 | "https://codecov.io/gh/googleapis/", 5 | "www.googleapis.com", 6 | "img.shields.io", 7 | "https://console.cloud.google.com/cloudshell", 8 | "https://support.google.com" 9 | ], 10 | "silent": true, 11 | "concurrency": 5, 12 | "retry": true, 13 | "retryErrors": true, 14 | "retryErrorsCount": 5, 15 | "retryErrorsJitter": 3000 16 | } 17 | -------------------------------------------------------------------------------- /owlbot.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 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 | # http://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 | from synthtool.languages import node 16 | 17 | # Main OwlBot processing. 18 | node.owlbot_main(templates_excludes=[ 19 | 'src/index.ts', 20 | '.github/PULL_REQUEST_TEMPLATE.md', 21 | '.github/release-please.yml', 22 | '.github/header-checker-lint.yaml', 23 | '.eslintignore' 24 | ]) 25 | -------------------------------------------------------------------------------- /protos/google/cloud/common_resources.proto: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | // http://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 | // This file contains stub messages for common resources in GCP. 16 | // It is not intended to be directly generated, and is instead used by 17 | // other tooling to be able to match common resource patterns. 18 | syntax = "proto3"; 19 | 20 | package google.cloud; 21 | 22 | import "google/api/resource.proto"; 23 | 24 | 25 | option (google.api.resource_definition) = { 26 | type: "cloudresourcemanager.googleapis.com/Project" 27 | pattern: "projects/{project}" 28 | }; 29 | 30 | 31 | option (google.api.resource_definition) = { 32 | type: "cloudresourcemanager.googleapis.com/Organization" 33 | pattern: "organizations/{organization}" 34 | }; 35 | 36 | 37 | option (google.api.resource_definition) = { 38 | type: "cloudresourcemanager.googleapis.com/Folder" 39 | pattern: "folders/{folder}" 40 | }; 41 | 42 | 43 | option (google.api.resource_definition) = { 44 | type: "cloudbilling.googleapis.com/BillingAccount" 45 | pattern: "billingAccounts/{billing_account}" 46 | }; 47 | 48 | option (google.api.resource_definition) = { 49 | type: "locations.googleapis.com/Location" 50 | pattern: "projects/{project}/locations/{location}" 51 | }; 52 | 53 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base", 4 | "docker:disable", 5 | ":disableDependencyDashboard" 6 | ], 7 | "constraintsFiltering": "strict", 8 | "pinVersions": false, 9 | "rebaseStalePrs": true, 10 | "schedule": [ 11 | "after 9am and before 3pm" 12 | ], 13 | "gitAuthor": null, 14 | "packageRules": [ 15 | { 16 | "extends": "packages:linters", 17 | "groupName": "linters" 18 | } 19 | ], 20 | "ignoreDeps": ["typescript"] 21 | } 22 | -------------------------------------------------------------------------------- /samples/.eslintrc.yml: -------------------------------------------------------------------------------- 1 | --- 2 | rules: 3 | no-console: off 4 | no-process-exit: off 5 | -------------------------------------------------------------------------------- /samples/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | -------------------------------------------------------------------------------- /samples/createAvroSchema.js: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * schemas with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Create an Avro based Schema 29 | // description: Creates a new schema definition on a project, using Avro 30 | // usage: node createAvroSchema.js 31 | 32 | // [START pubsub_create_avro_schema] 33 | /** 34 | * TODO(developer): Uncomment these variables before running the sample. 35 | */ 36 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 37 | // const avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json'; 38 | 39 | // Imports the Google Cloud client library 40 | const {PubSub, SchemaTypes} = require('@google-cloud/pubsub'); 41 | 42 | const fs = require('fs'); 43 | 44 | // Creates a client; cache this for further use 45 | const pubSubClient = new PubSub(); 46 | 47 | async function createAvroSchema(schemaNameOrId, avscFile) { 48 | const definition = fs.readFileSync(avscFile).toString(); 49 | const schema = await pubSubClient.createSchema( 50 | schemaNameOrId, 51 | SchemaTypes.Avro, 52 | definition, 53 | ); 54 | 55 | const name = await schema.getName(); 56 | console.log(`Schema ${name} created.`); 57 | } 58 | // [END pubsub_create_avro_schema] 59 | 60 | function main( 61 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 62 | avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json', 63 | ) { 64 | createAvroSchema(schemaNameOrId, avscFile).catch(err => { 65 | console.error(err.message); 66 | process.exitCode = 1; 67 | }); 68 | } 69 | 70 | main(...process.argv.slice(2)); 71 | -------------------------------------------------------------------------------- /samples/createSubscription.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This sample demonstrates how to create subscriptions with the 21 | * Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Create Subscription 29 | // description: Creates a new subscription. 30 | // usage: node createSubscription.js 31 | 32 | // [START pubsub_create_pull_subscription] 33 | /** 34 | * TODO(developer): Uncomment these variables before running the sample. 35 | */ 36 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 37 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 38 | 39 | // Imports the Google Cloud client library 40 | const {PubSub} = require('@google-cloud/pubsub'); 41 | 42 | // Creates a client; cache this for further use 43 | const pubSubClient = new PubSub(); 44 | 45 | async function createSubscription(topicNameOrId, subscriptionNameOrId) { 46 | // Creates a new subscription 47 | await pubSubClient 48 | .topic(topicNameOrId) 49 | .createSubscription(subscriptionNameOrId); 50 | console.log(`Subscription ${subscriptionNameOrId} created.`); 51 | } 52 | // [END pubsub_create_pull_subscription] 53 | 54 | function main( 55 | topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', 56 | subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', 57 | ) { 58 | createSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { 59 | console.error(err.message); 60 | process.exitCode = 1; 61 | }); 62 | } 63 | 64 | main(...process.argv.slice(2)); 65 | -------------------------------------------------------------------------------- /samples/createTopic.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This sample demonstrates how to perform basic operations on topics with 21 | * the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Create Topic 29 | // description: Creates a new topic. 30 | // usage: node createTopic.js 31 | 32 | // [START pubsub_create_topic] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function createTopic(topicNameOrId) { 45 | // Creates a new topic 46 | await pubSubClient.createTopic(topicNameOrId); 47 | console.log(`Topic ${topicNameOrId} created.`); 48 | } 49 | // [END pubsub_create_topic] 50 | 51 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 52 | createTopic(topicNameOrId).catch(err => { 53 | console.error(err.message); 54 | process.exitCode = 1; 55 | }); 56 | } 57 | 58 | main(...process.argv.slice(2)); 59 | -------------------------------------------------------------------------------- /samples/deleteSchema.js: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * schemas with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Delete a previously created schema 29 | // description: Deletes a schema which was previously created in the project. 30 | // usage: node deleteSchema.js 31 | 32 | // [START pubsub_delete_schema] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function deleteSchema(schemaNameOrId) { 45 | const schema = pubSubClient.schema(schemaNameOrId); 46 | const name = await schema.getName(); 47 | await schema.delete(); 48 | console.log(`Schema ${name} deleted.`); 49 | } 50 | // [END pubsub_delete_schema] 51 | 52 | function main(schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID') { 53 | deleteSchema(schemaNameOrId).catch(err => { 54 | console.error(err.message); 55 | process.exitCode = 1; 56 | }); 57 | } 58 | 59 | main(...process.argv.slice(2)); 60 | -------------------------------------------------------------------------------- /samples/deleteSubscription.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * subscriptions with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Delete Subscription 29 | // description: Deletes an existing subscription from a topic. 30 | // usage: node deleteSubscription.js 31 | 32 | // [START pubsub_delete_subscription] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function deleteSubscription(subscriptionNameOrId) { 45 | // Deletes the subscription 46 | await pubSubClient.subscription(subscriptionNameOrId).delete(); 47 | console.log(`Subscription ${subscriptionNameOrId} deleted.`); 48 | } 49 | // [END pubsub_delete_subscription] 50 | 51 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 52 | deleteSubscription(subscriptionNameOrId).catch(err => { 53 | console.error(err.message); 54 | process.exitCode = 1; 55 | }); 56 | } 57 | 58 | main(...process.argv.slice(2)); 59 | -------------------------------------------------------------------------------- /samples/deleteTopic.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This sample demonstrates how to perform basic operations on topics with 21 | * the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Delete Topic 29 | // description: Deletes an existing topic. 30 | // usage: node deleteTopic.js 31 | 32 | // [START pubsub_delete_topic] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function deleteTopic(topicNameOrId) { 45 | /** 46 | * TODO(developer): Uncomment the following line to run the sample. 47 | */ 48 | // const topicName = 'my-topic'; 49 | 50 | // Deletes the topic 51 | await pubSubClient.topic(topicNameOrId).delete(); 52 | console.log(`Topic ${topicNameOrId} deleted.`); 53 | } 54 | // [END pubsub_delete_topic] 55 | 56 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 57 | deleteTopic(topicNameOrId).catch(err => { 58 | console.error(err.message); 59 | process.exitCode = 1; 60 | }); 61 | } 62 | 63 | main(...process.argv.slice(2)); 64 | -------------------------------------------------------------------------------- /samples/getSchema.js: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * schemas with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Get a previously created schema 29 | // description: Gets information about a schema which was previously created in the project. 30 | // usage: node getSchema.js 31 | 32 | // [START pubsub_get_schema] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function getSchema(schemaNameOrId) { 45 | const schema = pubSubClient.schema(schemaNameOrId); 46 | const info = await schema.get(); 47 | const fullName = await schema.getName(); 48 | console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`); 49 | } 50 | // [END pubsub_get_schema] 51 | 52 | function main(schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID') { 53 | getSchema(schemaNameOrId).catch(err => { 54 | console.error(err.message); 55 | process.exitCode = 1; 56 | }); 57 | } 58 | 59 | main(...process.argv.slice(2)); 60 | -------------------------------------------------------------------------------- /samples/getSubscription.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2020 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | 'use strict'; 24 | 25 | // sample-metadata: 26 | // title: Get Subscription 27 | // description: Gets the metadata for a subscription. 28 | // usage: node getSubscription.js 29 | 30 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 31 | /** 32 | * TODO(developer): Uncomment this variable before running the sample. 33 | */ 34 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 35 | 36 | // Imports the Google Cloud client library 37 | const {PubSub} = require('@google-cloud/pubsub'); 38 | 39 | // Creates a client; cache this for further use 40 | const pubSubClient = new PubSub(); 41 | 42 | async function getSubscription() { 43 | // Gets the metadata for the subscription 44 | const [metadata] = await pubSubClient 45 | .subscription(subscriptionNameOrId) 46 | .getMetadata(); 47 | 48 | console.log(`Subscription: ${metadata.name}`); 49 | console.log(`Topic: ${metadata.topic}`); 50 | console.log(`Push config: ${metadata.pushConfig.pushEndpoint}`); 51 | console.log(`Ack deadline: ${metadata.ackDeadlineSeconds}s`); 52 | } 53 | 54 | getSubscription().catch(console.error); 55 | } 56 | 57 | main(...process.argv.slice(2)); 58 | -------------------------------------------------------------------------------- /samples/getSubscriptionPolicy.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * subscriptions with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Get Subscription Policy 29 | // description: Gets the IAM policy for a subscription. 30 | // usage: node getSubscriptionPolicy.js 31 | 32 | // [START pubsub_get_subscription_policy] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function getSubscriptionPolicy(subscriptionNameOrId) { 45 | // Retrieves the IAM policy for the subscription 46 | const [policy] = await pubSubClient 47 | .subscription(subscriptionNameOrId) 48 | .iam.getPolicy(); 49 | 50 | console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`); 51 | } 52 | // [END pubsub_get_subscription_policy] 53 | 54 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 55 | getSubscriptionPolicy(subscriptionNameOrId).catch(err => { 56 | console.error(err.message); 57 | process.exitCode = 1; 58 | }); 59 | } 60 | 61 | main(...process.argv.slice(2)); 62 | -------------------------------------------------------------------------------- /samples/getTopicPolicy.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This sample demonstrates how to perform basic operations on topics with 21 | * the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Get Topic Policy 29 | // description: Gets the IAM policy for a topic. 30 | // usage: node getTopicPolicy.js 31 | 32 | // [START pubsub_get_topic_policy] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function getTopicPolicy(topicNameOrId) { 45 | // Retrieves the IAM policy for the topic 46 | const [policy] = await pubSubClient.topic(topicNameOrId).iam.getPolicy(); 47 | console.log('Policy for topic: %j.', policy.bindings); 48 | } 49 | // [END pubsub_get_topic_policy] 50 | 51 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 52 | getTopicPolicy(topicNameOrId).catch(err => { 53 | console.error(err.message); 54 | process.exitCode = 1; 55 | }); 56 | } 57 | 58 | main(...process.argv.slice(2)); 59 | -------------------------------------------------------------------------------- /samples/listAllTopics.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This sample demonstrates how to perform basic operations on topics with 21 | * the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: List All Topics 29 | // description: Lists all topics in the current project. 30 | // usage: node listAllTopics.js 31 | 32 | // [START pubsub_list_topics] 33 | // Imports the Google Cloud client library 34 | const {PubSub} = require('@google-cloud/pubsub'); 35 | 36 | // Creates a client; cache this for further use 37 | const pubSubClient = new PubSub(); 38 | 39 | async function listAllTopics() { 40 | // Lists all topics in the current project 41 | const [topics] = await pubSubClient.getTopics(); 42 | console.log('Topics:'); 43 | topics.forEach(topic => console.log(topic.name)); 44 | } 45 | // [END pubsub_list_topics] 46 | 47 | function main() { 48 | listAllTopics().catch(err => { 49 | console.error(err.message); 50 | process.exitCode = 1; 51 | }); 52 | } 53 | 54 | main(); 55 | -------------------------------------------------------------------------------- /samples/listSchemas.js: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * schemas with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: List schemas on a project 29 | // description: Gets a list of schemas which were previously created in the project. 30 | // usage: node listSchemas.js 31 | 32 | // [START pubsub_list_schemas] 33 | 34 | // Imports the Google Cloud client library 35 | const {PubSub} = require('@google-cloud/pubsub'); 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function listSchemas() { 41 | for await (const s of pubSubClient.listSchemas()) { 42 | console.log(s.name); 43 | } 44 | console.log('Listed schemas.'); 45 | } 46 | // [END pubsub_list_schemas] 47 | 48 | function main() { 49 | listSchemas().catch(err => { 50 | console.error(err.message); 51 | process.exitCode = 1; 52 | }); 53 | } 54 | 55 | main(); 56 | -------------------------------------------------------------------------------- /samples/listSubscriptions.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * subscriptions with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: List Subscriptions 29 | // description: Lists all subscriptions in the current project. 30 | // usage: node listSubscriptions.js 31 | 32 | // [START pubsub_list_subscriptions] 33 | // Imports the Google Cloud client library 34 | const {PubSub} = require('@google-cloud/pubsub'); 35 | 36 | // Creates a client; cache this for further use 37 | const pubSubClient = new PubSub(); 38 | 39 | async function listSubscriptions() { 40 | // Lists all subscriptions in the current project 41 | const [subscriptions] = await pubSubClient.getSubscriptions(); 42 | console.log('Subscriptions:'); 43 | subscriptions.forEach(subscription => console.log(subscription.name)); 44 | } 45 | // [END pubsub_list_subscriptions] 46 | 47 | function main() { 48 | listSubscriptions().catch(console.error); 49 | } 50 | 51 | main(); 52 | -------------------------------------------------------------------------------- /samples/listTopicSubscriptions.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * subscriptions with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: List Subscriptions On a Topic 29 | // description: Lists all subscriptions in the current project, filtering by a topic. 30 | // usage: node listTopicSubscriptions.js 31 | 32 | // [START pubsub_list_topic_subscriptions] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function listTopicSubscriptions(topicNameOrId) { 45 | // Lists all subscriptions for the topic 46 | const [subscriptions] = await pubSubClient 47 | .topic(topicNameOrId) 48 | .getSubscriptions(); 49 | 50 | console.log(`Subscriptions for ${topicNameOrId}:`); 51 | subscriptions.forEach(subscription => console.log(subscription.name)); 52 | } 53 | // [END pubsub_list_topic_subscriptions] 54 | 55 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 56 | listTopicSubscriptions(topicNameOrId).catch(err => { 57 | console.error(err.message); 58 | process.exitCode = 1; 59 | }); 60 | } 61 | 62 | main(...process.argv.slice(2)); 63 | -------------------------------------------------------------------------------- /samples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-docs-samples-pubsub", 3 | "files": [ 4 | "*.js", 5 | "typescript/*.ts" 6 | ], 7 | "private": true, 8 | "license": "Apache-2.0", 9 | "author": "Google Inc.", 10 | "repository": "googleapis/nodejs-pubsub", 11 | "engines": { 12 | "node": ">=18" 13 | }, 14 | "scripts": { 15 | "test": "mocha build/system-test --timeout 600000", 16 | "pretest": "npm run compile && cp -f *.js build/", 17 | "tsc": "tsc -p .", 18 | "sampletsc": "cd typescript && tsc -p . && cd ..", 19 | "compile": "npm run tsc && npm run sampletsc", 20 | "clean": "gts clean && rm -rf build/", 21 | "precompile": "npm run clean", 22 | "pretypeless": "npx eslint --fix typescript/*.ts", 23 | "typeless": "npx typeless-sample-bot --outputpath . --targets typescript --recursive", 24 | "posttypeless": "npx eslint --fix *.js" 25 | }, 26 | "dependencies": { 27 | "@google-cloud/opentelemetry-cloud-trace-exporter": "^2.0.0", 28 | "@google-cloud/pubsub": "^5.0.0", 29 | "@google-cloud/storage": "^7.11.1", 30 | "@opentelemetry/api": "^1.6.0", 31 | "@opentelemetry/resources": "^1.17.0", 32 | "@opentelemetry/sdk-trace-base": "^1.17.0", 33 | "@opentelemetry/sdk-trace-node": "^1.17.0", 34 | "@opentelemetry/semantic-conventions": "^1.17.0", 35 | "avro-js": "^1.11.3", 36 | "p-defer": "^3.0.0", 37 | "protobufjs": "~7.5.0" 38 | }, 39 | "devDependencies": { 40 | "@google-cloud/bigquery": "^8.0.0", 41 | "@google-cloud/typeless-sample-bot": "^3.0.0", 42 | "@types/chai": "^4.2.16", 43 | "chai": "^4.2.0", 44 | "gts": "^6.0.0", 45 | "lru-cache": "9.1.2", 46 | "mocha": "^9.2.2", 47 | "rimraf": "5.0.9", 48 | "typescript": "^5.1.6", 49 | "uuid": "^9.0.0" 50 | } 51 | } -------------------------------------------------------------------------------- /samples/quickstart.js: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /* eslint-disable n/no-process-exit */ 20 | 21 | // sample-metadata: 22 | // title: Quickstart 23 | // description: A quick introduction to using the Pub/Sub client library. 24 | // usage: node quickstart.js 25 | 26 | // [START pubsub_quickstart_create_topic] 27 | // Imports the Google Cloud client library 28 | const {PubSub} = require('@google-cloud/pubsub'); 29 | 30 | async function quickstart( 31 | projectId = 'your-project-id', // Your Google Cloud Platform project ID 32 | topicNameOrId = 'my-topic', // Name for the new topic to create 33 | subscriptionName = 'my-sub', // Name for the new subscription to create 34 | ) { 35 | // Instantiates a client 36 | const pubsub = new PubSub({projectId}); 37 | 38 | // Creates a new topic 39 | const [topic] = await pubsub.createTopic(topicNameOrId); 40 | console.log(`Topic ${topic.name} created.`); 41 | 42 | // Creates a subscription on that new topic 43 | const [subscription] = await topic.createSubscription(subscriptionName); 44 | 45 | // Receive callbacks for new messages on the subscription 46 | subscription.on('message', message => { 47 | console.log('Received message:', message.data.toString()); 48 | process.exit(0); 49 | }); 50 | 51 | // Receive callbacks for errors on the subscription 52 | subscription.on('error', error => { 53 | console.error('Received error:', error); 54 | process.exit(1); 55 | }); 56 | 57 | // Send a message to the topic 58 | await topic.publishMessage({data: Buffer.from('Test message!')}); 59 | } 60 | // [END pubsub_quickstart_create_topic] 61 | 62 | quickstart(...process.argv.slice(2)).catch(err => { 63 | console.error(err.message); 64 | process.exitCode = 1; 65 | }); 66 | -------------------------------------------------------------------------------- /samples/rollbackSchema.js: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * schemas with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Rollback a Schema 29 | // description: Rolls back a schema on a project 30 | // usage: node rollbackSchema.js 31 | 32 | // [START pubsub_rollback_schema] 33 | /** 34 | * TODO(developer): Uncomment these variables before running the sample. 35 | */ 36 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 37 | // const revisionId = 'YOUR_REVISION_ID'; 38 | 39 | // Imports the Google Cloud client library 40 | const {PubSub} = require('@google-cloud/pubsub'); 41 | 42 | // Creates a client; cache this for further use 43 | const pubSubClient = new PubSub(); 44 | 45 | async function rollbackSchema(schemaNameOrId, revisionId) { 46 | // Get the fully qualified schema name. 47 | const schema = pubSubClient.schema(schemaNameOrId); 48 | const name = await schema.getName(); 49 | 50 | // Use the gapic client to roll back the schema revision. 51 | const schemaClient = await pubSubClient.getSchemaClient(); 52 | await schemaClient.rollbackSchema({ 53 | name, 54 | revisionId, 55 | }); 56 | 57 | console.log(`Schema ${name} revision ${revisionId} rolled back.`); 58 | } 59 | // [END pubsub_rollback_schema] 60 | 61 | function main( 62 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 63 | revisionId = 'YOUR_REVISION_ID', 64 | ) { 65 | rollbackSchema(schemaNameOrId, revisionId).catch(err => { 66 | console.error(err.message); 67 | process.exitCode = 1; 68 | }); 69 | } 70 | 71 | main(...process.argv.slice(2)); 72 | -------------------------------------------------------------------------------- /samples/system-test/common.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2022 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 | import {assert} from 'chai'; 16 | import {describe, it} from 'mocha'; 17 | import {commandFor} from './common'; 18 | import * as path from 'path'; 19 | 20 | describe('common (unit)', () => { 21 | it('commandFor finds TS samples', () => { 22 | const result = commandFor('createAvroSchema'); 23 | assert.strictEqual( 24 | result, 25 | `node ${path.join('build', 'createAvroSchema.js')}` 26 | ); 27 | }); 28 | 29 | it('commandFor finds JS samples', () => { 30 | const result = commandFor('createSubscription'); 31 | assert.strictEqual( 32 | result, 33 | `node ${path.join('build', 'createSubscription.js')}` 34 | ); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /samples/system-test/common.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | import * as cp from 'child_process'; 16 | import * as path from 'path'; 17 | 18 | export const execSync = (cmd: string): string => 19 | cp.execSync(cmd, {encoding: 'utf-8'}); 20 | 21 | // Processed versions of TS samples go to the same build location 22 | // as the rest of the JS samples. 23 | export function commandFor(action: string): string { 24 | const jsPath = path.join('build', `${action}.js`); 25 | return `node ${jsPath}`; 26 | } 27 | -------------------------------------------------------------------------------- /samples/system-test/fixtures/getSchema-expected.jstest: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // This is a generated sample. Please see typescript/README.md for more info. 24 | 25 | 'use strict'; 26 | 27 | // sample-metadata: 28 | // title: Get a previously created schema 29 | // description: Gets information about a schema which was previously created in the project. 30 | // usage: node getSchema.js 31 | 32 | /** 33 | * TODO(developer): Uncomment this variable before running the sample. 34 | */ 35 | // const schemaName = 'YOUR_SCHEMA_NAME'; 36 | 37 | // Imports the Google Cloud client library 38 | const {PubSub} = require('@google-cloud/pubsub'); 39 | 40 | // Creates a client; cache this for further use 41 | const pubSubClient = new PubSub(); 42 | 43 | async function getSchema(schemaName) { 44 | const schema = pubSubClient.schema(schemaName); 45 | const info = await schema.get(); 46 | const fullName = await schema.getName(); 47 | console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`); 48 | } 49 | 50 | function main(schemaName = 'YOUR_SCHEMA_NAME') { 51 | getSchema(schemaName).catch(err => { 52 | console.error(err.message); 53 | process.exitCode = 1; 54 | }); 55 | } 56 | 57 | main(...process.argv.slice(2)); 58 | -------------------------------------------------------------------------------- /samples/system-test/fixtures/getSchema-expected.tstest: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | //BLANK 15 | /** 16 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | //BLANK 23 | // sample-metadata: 24 | // title: Get a previously created schema 25 | // description: Gets information about a schema which was previously created in the project. 26 | // usage: node getSchema.js 27 | //BLANK 28 | /** 29 | * TODO(developer): Uncomment this variable before running the sample. 30 | */ 31 | // const schemaName = 'YOUR_SCHEMA_NAME'; 32 | //BLANK 33 | // Imports the Google Cloud client library 34 | import {PubSub} from '@google-cloud/pubsub'; 35 | //BLANK 36 | // Creates a client; cache this for further use 37 | const pubSubClient = new PubSub(); 38 | //BLANK 39 | async function getSchema(schemaName: string) { 40 | const schema = pubSubClient.schema(schemaName); 41 | const info = await schema.get(); 42 | const fullName = await schema.getName(); 43 | console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`); 44 | } 45 | //BLANK 46 | function main(schemaName = 'YOUR_SCHEMA_NAME') { 47 | getSchema(schemaName).catch(err => { 48 | console.error(err.message); 49 | process.exitCode = 1; 50 | }); 51 | } 52 | //BLANK 53 | main(...process.argv.slice(2)); 54 | -------------------------------------------------------------------------------- /samples/system-test/fixtures/getSchema-fixture.jstest: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | //BLANK 15 | /** 16 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | //BLANK 23 | // sample-metadata: 24 | // title: Get a previously created schema 25 | // description: Gets information about a schema which was previously created in the project. 26 | // usage: node getSchema.js 27 | //BLANK 28 | /** 29 | * TODO(developer): Uncomment this variable before running the sample. 30 | */ 31 | // const schemaName = 'YOUR_SCHEMA_NAME'; 32 | //BLANK 33 | // Imports the Google Cloud client library 34 | import { PubSub } from '@google-cloud/pubsub'; 35 | //BLANK 36 | // Creates a client; cache this for further use 37 | const pubSubClient = new PubSub(); 38 | //BLANK 39 | async function getSchema(schemaName) { 40 | const schema = pubSubClient.schema(schemaName); 41 | const info = await schema.get(); 42 | const fullName = await schema.getName(); 43 | console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`); 44 | } 45 | //BLANK 46 | function main(schemaName = 'YOUR_SCHEMA_NAME') { 47 | getSchema(schemaName).catch(err => { 48 | console.error(err.message); 49 | process.exitCode = 1; 50 | }); 51 | } 52 | //BLANK 53 | main(...process.argv.slice(2)); 54 | -------------------------------------------------------------------------------- /samples/system-test/fixtures/getSchema-fixture.tstest: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Get a previously created schema 25 | // description: Gets information about a schema which was previously created in the project. 26 | // usage: node getSchema.js 27 | 28 | /** 29 | * TODO(developer): Uncomment this variable before running the sample. 30 | */ 31 | // const schemaName = 'YOUR_SCHEMA_NAME'; 32 | 33 | // Imports the Google Cloud client library 34 | import {PubSub} from '@google-cloud/pubsub'; 35 | 36 | // Creates a client; cache this for further use 37 | const pubSubClient = new PubSub(); 38 | 39 | async function getSchema(schemaName: string) { 40 | const schema = pubSubClient.schema(schemaName); 41 | const info = await schema.get(); 42 | const fullName = await schema.getName(); 43 | console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`); 44 | } 45 | 46 | function main(schemaName = 'YOUR_SCHEMA_NAME') { 47 | getSchema(schemaName).catch(err => { 48 | console.error(err.message); 49 | process.exitCode = 1; 50 | }); 51 | } 52 | 53 | main(...process.argv.slice(2)); 54 | -------------------------------------------------------------------------------- /samples/system-test/fixtures/provinces.avsc: -------------------------------------------------------------------------------- 1 | { 2 | "type":"record", 3 | "name":"Province", 4 | "namespace":"utilities", 5 | "doc":"A list of provinces in Canada.", 6 | "fields":[ 7 | { 8 | "name":"name", 9 | "type":"string", 10 | "doc":"The common name of the province." 11 | }, 12 | { 13 | "name":"post_abbr", 14 | "type":"string", 15 | "doc":"The postal code abbreviation of the province." 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /samples/system-test/fixtures/provinces.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package utilities; 4 | 5 | message Province { 6 | string name = 1; 7 | string post_abbr = 2; 8 | } 9 | -------------------------------------------------------------------------------- /samples/system-test/openTelemetryTracing.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | import {PubSub} from '@google-cloud/pubsub'; 16 | import {assert} from 'chai'; 17 | import {describe, it, before, after} from 'mocha'; 18 | import {execSync, commandFor} from './common'; 19 | import {TestResources} from './testResources'; 20 | 21 | describe('openTelemetry', () => { 22 | const projectId = process.env.GCLOUD_PROJECT; 23 | const pubsub = new PubSub({projectId}); 24 | 25 | const resources = new TestResources('otel'); 26 | const topicName = resources.generateName('ot'); 27 | const subName = resources.generateName('ot'); 28 | 29 | before(async () => { 30 | await pubsub.createTopic(topicName); 31 | await pubsub.topic(topicName).createSubscription(subName); 32 | }); 33 | 34 | after(async () => { 35 | const [subscriptions] = await pubsub.getSubscriptions(); 36 | await Promise.all( 37 | resources.filterForCleanup(subscriptions).map(x => x.delete?.()) 38 | ); 39 | 40 | const [topics] = await pubsub.getTopics(); 41 | await Promise.all( 42 | resources.filterForCleanup(topics).map(x => x.delete?.()) 43 | ); 44 | }); 45 | 46 | it('should run the WithOpenTelemetryTracing samples', async () => { 47 | const stdout = execSync( 48 | `${commandFor('publishWithOpenTelemetryTracing')} ${topicName}` 49 | ); 50 | assert.match(stdout, /Message .* published./); 51 | assert.match(stdout, /Cloud Trace batch writing traces/); 52 | assert.match(stdout, /batchWriteSpans successfully/); 53 | assert.notMatch(stdout, /Received error/); 54 | 55 | const stdoutSub = execSync( 56 | `${commandFor('listenWithOpenTelemetryTracing')} ${subName}` 57 | ); 58 | assert.match(stdoutSub, /Message .* received/); 59 | assert.match(stdoutSub, /Cloud Trace batch writing traces/); 60 | assert.match(stdoutSub, /batchWriteSpans successfully/); 61 | assert.notMatch(stdoutSub, /Received error/); 62 | }); 63 | }); 64 | -------------------------------------------------------------------------------- /samples/system-test/quickstart.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2017 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 | // http://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 | import {PubSub} from '@google-cloud/pubsub'; 16 | import {assert} from 'chai'; 17 | import {describe, it, after} from 'mocha'; 18 | import {execSync, commandFor} from './common'; 19 | import {TestResources} from './testResources'; 20 | 21 | describe('quickstart', () => { 22 | const projectId = process.env.GCLOUD_PROJECT; 23 | const pubsub = new PubSub({projectId}); 24 | 25 | const resources = new TestResources('quickstart'); 26 | const topicName = resources.generateName('qs'); 27 | const subName = resources.generateName('qs'); 28 | 29 | after(async () => { 30 | const [subscriptions] = await pubsub.getSubscriptions(); 31 | await Promise.all( 32 | resources.filterForCleanup(subscriptions).map(x => x.delete?.()) 33 | ); 34 | 35 | const [topics] = await pubsub.getTopics(); 36 | await Promise.all( 37 | resources.filterForCleanup(topics).map(x => x.delete?.()) 38 | ); 39 | }); 40 | 41 | it('should run the quickstart', async () => { 42 | const stdout = execSync( 43 | `${commandFor('quickstart')} ${projectId} ${topicName} ${subName}` 44 | ); 45 | assert.match(stdout, /^Topic .* created./); 46 | assert.match(stdout, /Received message.*Test/); 47 | assert.notMatch(stdout, /Received error/); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /samples/testSubscriptionPermissions.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This application demonstrates how to perform basic operations on 21 | * subscriptions with the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Test Subscription Permissions 29 | // description: Tests the permissions for a subscription. 30 | // usage: node testSubscriptionPermissions.js 31 | 32 | // [START pubsub_test_subscription_permissions] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function testSubscriptionPermissions(subscriptionNameOrId) { 45 | const permissionsToTest = [ 46 | 'pubsub.subscriptions.consume', 47 | 'pubsub.subscriptions.update', 48 | ]; 49 | 50 | // Tests the IAM policy for the specified subscription 51 | const [permissions] = await pubSubClient 52 | .subscription(subscriptionNameOrId) 53 | .iam.testPermissions(permissionsToTest); 54 | 55 | console.log('Tested permissions for subscription: %j', permissions); 56 | } 57 | // [END pubsub_test_subscription_permissions] 58 | 59 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 60 | testSubscriptionPermissions(subscriptionNameOrId).catch(err => { 61 | console.error(err.message); 62 | process.exitCode = 1; 63 | }); 64 | } 65 | 66 | main(...process.argv.slice(2)); 67 | -------------------------------------------------------------------------------- /samples/testTopicPermissions.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // This is a generated sample, using the typeless sample bot. Please 16 | // look for the source TypeScript sample (.ts) for modifications. 17 | 'use strict'; 18 | 19 | /** 20 | * This sample demonstrates how to perform basic operations on topics with 21 | * the Google Cloud Pub/Sub API. 22 | * 23 | * For more information, see the README.md under /pubsub and the documentation 24 | * at https://cloud.google.com/pubsub/docs. 25 | */ 26 | 27 | // sample-metadata: 28 | // title: Test Topic Permissions 29 | // description: Tests the permissions for a topic. 30 | // usage: node testTopicPermissions.js 31 | 32 | // [START pubsub_test_topic_permissions] 33 | /** 34 | * TODO(developer): Uncomment this variable before running the sample. 35 | */ 36 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 37 | 38 | // Imports the Google Cloud client library 39 | const {PubSub} = require('@google-cloud/pubsub'); 40 | 41 | // Creates a client; cache this for further use 42 | const pubSubClient = new PubSub(); 43 | 44 | async function testTopicPermissions(topicNameOrId) { 45 | const permissionsToTest = [ 46 | 'pubsub.topics.attachSubscription', 47 | 'pubsub.topics.publish', 48 | 'pubsub.topics.update', 49 | ]; 50 | 51 | // Tests the IAM policy for the specified topic 52 | const [permissions] = await pubSubClient 53 | .topic(topicNameOrId) 54 | .iam.testPermissions(permissionsToTest); 55 | 56 | console.log('Tested permissions for topic: %j', permissions); 57 | } 58 | // [END pubsub_test_topic_permissions] 59 | 60 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 61 | testTopicPermissions(topicNameOrId).catch(err => { 62 | console.error(err.message); 63 | process.exitCode = 1; 64 | }); 65 | } 66 | 67 | main(...process.argv.slice(2)); 68 | -------------------------------------------------------------------------------- /samples/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "build", 6 | "resolveJsonModule": true, 7 | "lib": [ 8 | "es2018", 9 | "dom" 10 | ], 11 | "moduleResolution": "node" 12 | }, 13 | "include": [ 14 | "system-test/*.ts", 15 | "typescript/*.ts" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /samples/typescript/README.md: -------------------------------------------------------------------------------- 1 | # About TypeScript samples 2 | 3 | In order to provide better samples for our TypeScript users, new samples going forward will be written in TypeScript, in this directory. `npm run compile` will take care of all the steps needed to merge the existing JavaScript samples into `build/` along with the converted TypeScript samples. The system sample tests will then use `build/` for its testing. 4 | 5 | Note that the files `tsc` builds from this tree will not be used; this is just to do strict type checking. 6 | 7 | When you are ready to submit a PR for the updated sample, OwlBot will take care of regenerating any `*.js` files from the `*.ts` files. 8 | -------------------------------------------------------------------------------- /samples/typescript/avro-js.d.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | // This one doesn't seem to have typings. 16 | declare module 'avro-js' { 17 | function parse(def: string): Parser; 18 | 19 | class Parser { 20 | fromBuffer(buf: Buffer): T; 21 | fromString(str: string): T; 22 | toBuffer(item: T): Buffer; 23 | toString(item: T): string; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /samples/typescript/createAvroSchema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Create an Avro based Schema 25 | // description: Creates a new schema definition on a project, using Avro 26 | // usage: node createAvroSchema.js 27 | 28 | // [START pubsub_create_avro_schema] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | // const avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub, SchemaTypes} from '@google-cloud/pubsub'; 37 | 38 | import * as fs from 'fs'; 39 | 40 | // Creates a client; cache this for further use 41 | const pubSubClient = new PubSub(); 42 | 43 | async function createAvroSchema(schemaNameOrId: string, avscFile: string) { 44 | const definition: string = fs.readFileSync(avscFile).toString(); 45 | const schema = await pubSubClient.createSchema( 46 | schemaNameOrId, 47 | SchemaTypes.Avro, 48 | definition, 49 | ); 50 | 51 | const name = await schema.getName(); 52 | console.log(`Schema ${name} created.`); 53 | } 54 | // [END pubsub_create_avro_schema] 55 | 56 | function main( 57 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 58 | avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json', 59 | ) { 60 | createAvroSchema(schemaNameOrId, avscFile).catch(err => { 61 | console.error(err.message); 62 | process.exitCode = 1; 63 | }); 64 | } 65 | 66 | main(...process.argv.slice(2)); 67 | -------------------------------------------------------------------------------- /samples/typescript/createProtoSchema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Create a Proto based Schema 25 | // description: Creates a new schema definition on a project, using Protos 26 | // usage: node createProtoSchema.js 27 | 28 | // [START pubsub_create_proto_schema] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | // const protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub, SchemaTypes} from '@google-cloud/pubsub'; 37 | 38 | import * as fs from 'fs'; 39 | 40 | // Creates a client; cache this for further use 41 | const pubSubClient = new PubSub(); 42 | 43 | async function createProtoSchema(schemaNameOrId: string, protoFile: string) { 44 | const definition: string = fs.readFileSync(protoFile).toString(); 45 | const schema = await pubSubClient.createSchema( 46 | schemaNameOrId, 47 | SchemaTypes.ProtocolBuffer, 48 | definition, 49 | ); 50 | 51 | const fullName: string = await schema.getName(); 52 | console.log(`Schema ${fullName} created.`); 53 | } 54 | // [END pubsub_create_proto_schema] 55 | 56 | function main( 57 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 58 | protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers', 59 | ) { 60 | createProtoSchema(schemaNameOrId, protoFile).catch(err => { 61 | console.error(err.message); 62 | process.exitCode = 1; 63 | }); 64 | } 65 | 66 | main(...process.argv.slice(2)); 67 | -------------------------------------------------------------------------------- /samples/typescript/createSubscription.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This sample demonstrates how to create subscriptions with the 17 | * Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Create Subscription 25 | // description: Creates a new subscription. 26 | // usage: node createSubscription.js 27 | 28 | // [START pubsub_create_pull_subscription] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub} from '@google-cloud/pubsub'; 37 | 38 | // Creates a client; cache this for further use 39 | const pubSubClient = new PubSub(); 40 | 41 | async function createSubscription( 42 | topicNameOrId: string, 43 | subscriptionNameOrId: string, 44 | ) { 45 | // Creates a new subscription 46 | await pubSubClient 47 | .topic(topicNameOrId) 48 | .createSubscription(subscriptionNameOrId); 49 | console.log(`Subscription ${subscriptionNameOrId} created.`); 50 | } 51 | // [END pubsub_create_pull_subscription] 52 | 53 | function main( 54 | topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', 55 | subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', 56 | ) { 57 | createSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { 58 | console.error(err.message); 59 | process.exitCode = 1; 60 | }); 61 | } 62 | 63 | main(...process.argv.slice(2)); 64 | -------------------------------------------------------------------------------- /samples/typescript/createSubscriptionWithRetryPolicy.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2023 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 | // http://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 | * This sample demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Create Subscription With Retry Policy 25 | // description: Creates a new subscription with a retry policy. 26 | // usage: node createSubscriptionWithRetryPolicy.js 27 | 28 | /** 29 | * TODO(developer): Uncomment these variables before running the sample. 30 | */ 31 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 32 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function createSubscriptionWithRetryPolicy( 41 | topicNameOrId: string, 42 | subscriptionNameOrId: string, 43 | ) { 44 | // Creates a new subscription 45 | await pubSubClient 46 | .topic(topicNameOrId) 47 | .createSubscription(subscriptionNameOrId, { 48 | retryPolicy: { 49 | minimumBackoff: { 50 | seconds: 60, 51 | }, 52 | maximumBackoff: { 53 | seconds: 600, 54 | }, 55 | }, 56 | }); 57 | console.log( 58 | `Created subscription ${subscriptionNameOrId} with retry policy.`, 59 | ); 60 | } 61 | 62 | function main( 63 | topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', 64 | subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', 65 | ) { 66 | createSubscriptionWithRetryPolicy(topicNameOrId, subscriptionNameOrId).catch( 67 | err => { 68 | console.error(err.message); 69 | process.exitCode = 1; 70 | }, 71 | ); 72 | } 73 | 74 | main(...process.argv.slice(2)); 75 | -------------------------------------------------------------------------------- /samples/typescript/createTopic.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | * This sample demonstrates how to perform basic operations on topics with 17 | * the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Create Topic 25 | // description: Creates a new topic. 26 | // usage: node createTopic.js 27 | 28 | // [START pubsub_create_topic] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function createTopic(topicNameOrId: string) { 41 | // Creates a new topic 42 | await pubSubClient.createTopic(topicNameOrId); 43 | console.log(`Topic ${topicNameOrId} created.`); 44 | } 45 | // [END pubsub_create_topic] 46 | 47 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 48 | createTopic(topicNameOrId).catch(err => { 49 | console.error(err.message); 50 | process.exitCode = 1; 51 | }); 52 | } 53 | 54 | main(...process.argv.slice(2)); 55 | -------------------------------------------------------------------------------- /samples/typescript/deleteSchema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Delete a previously created schema 25 | // description: Deletes a schema which was previously created in the project. 26 | // usage: node deleteSchema.js 27 | 28 | // [START pubsub_delete_schema] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function deleteSchema(schemaNameOrId: string) { 41 | const schema = pubSubClient.schema(schemaNameOrId); 42 | const name = await schema.getName(); 43 | await schema.delete(); 44 | console.log(`Schema ${name} deleted.`); 45 | } 46 | // [END pubsub_delete_schema] 47 | 48 | function main(schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID') { 49 | deleteSchema(schemaNameOrId).catch(err => { 50 | console.error(err.message); 51 | process.exitCode = 1; 52 | }); 53 | } 54 | 55 | main(...process.argv.slice(2)); 56 | -------------------------------------------------------------------------------- /samples/typescript/deleteSchemaRevision.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Delete a Schema Revision 25 | // description: Deletes a schema revision on a project 26 | // usage: node deleteSchemaRevision.js 27 | 28 | // [START pubsub_delete_schema_revision] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | // const revisionId = 'YOUR_REVISION_ID'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub} from '@google-cloud/pubsub'; 37 | 38 | // Creates a client; cache this for further use 39 | const pubSubClient = new PubSub(); 40 | 41 | async function deleteSchemaRevision( 42 | schemaNameOrId: string, 43 | revisionId: string, 44 | ) { 45 | // Get the fully qualified schema name. 46 | const schema = pubSubClient.schema(schemaNameOrId); 47 | const name = await schema.getName(); 48 | 49 | // Use the gapic client to delete the schema revision. 50 | const schemaClient = await pubSubClient.getSchemaClient(); 51 | await schemaClient.deleteSchemaRevision({ 52 | name: `${name}@${revisionId}`, 53 | }); 54 | 55 | console.log(`Schema ${name} revision ${revisionId} deleted.`); 56 | } 57 | // [END pubsub_delete_schema_revision] 58 | 59 | function main( 60 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 61 | revisionId = 'YOUR_REVISION_ID', 62 | ) { 63 | deleteSchemaRevision(schemaNameOrId, revisionId).catch(err => { 64 | console.error(err.message); 65 | process.exitCode = 1; 66 | }); 67 | } 68 | 69 | main(...process.argv.slice(2)); 70 | -------------------------------------------------------------------------------- /samples/typescript/deleteSubscription.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Delete Subscription 25 | // description: Deletes an existing subscription from a topic. 26 | // usage: node deleteSubscription.js 27 | 28 | // [START pubsub_delete_subscription] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function deleteSubscription(subscriptionNameOrId: string) { 41 | // Deletes the subscription 42 | await pubSubClient.subscription(subscriptionNameOrId).delete(); 43 | console.log(`Subscription ${subscriptionNameOrId} deleted.`); 44 | } 45 | // [END pubsub_delete_subscription] 46 | 47 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 48 | deleteSubscription(subscriptionNameOrId).catch(err => { 49 | console.error(err.message); 50 | process.exitCode = 1; 51 | }); 52 | } 53 | 54 | main(...process.argv.slice(2)); 55 | -------------------------------------------------------------------------------- /samples/typescript/deleteTopic.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | * This sample demonstrates how to perform basic operations on topics with 17 | * the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Delete Topic 25 | // description: Deletes an existing topic. 26 | // usage: node deleteTopic.js 27 | 28 | // [START pubsub_delete_topic] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function deleteTopic(topicNameOrId: string) { 41 | /** 42 | * TODO(developer): Uncomment the following line to run the sample. 43 | */ 44 | // const topicName = 'my-topic'; 45 | 46 | // Deletes the topic 47 | await pubSubClient.topic(topicNameOrId).delete(); 48 | console.log(`Topic ${topicNameOrId} deleted.`); 49 | } 50 | // [END pubsub_delete_topic] 51 | 52 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 53 | deleteTopic(topicNameOrId).catch(err => { 54 | console.error(err.message); 55 | process.exitCode = 1; 56 | }); 57 | } 58 | 59 | main(...process.argv.slice(2)); 60 | -------------------------------------------------------------------------------- /samples/typescript/detachSubscription.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2020-2023 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 | // http://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 | * This sample demonstrates how to detach subscriptions with the 17 | * Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Detach Subscription 25 | // description: Detaches a subscription from a topic. 26 | // usage: node detachSubscription.js 27 | 28 | // [START pubsub_detach_subscription] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function detachSubscription(subscriptionNameOrId: string) { 41 | // Gets the status of the existing subscription 42 | const sub = pubSubClient.subscription(subscriptionNameOrId); 43 | const [detached] = await sub.detached(); 44 | console.log( 45 | `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`, 46 | ); 47 | 48 | await pubSubClient.detachSubscription(subscriptionNameOrId); 49 | console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`); 50 | 51 | const [updatedDetached] = await sub.detached(); 52 | console.log( 53 | `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`, 54 | ); 55 | } 56 | // [END pubsub_detach_subscription] 57 | 58 | function main(subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID') { 59 | detachSubscription(subscriptionNameOrId).catch(err => { 60 | console.error(err.message); 61 | process.exitCode = 1; 62 | }); 63 | } 64 | 65 | main(...process.argv.slice(2)); 66 | -------------------------------------------------------------------------------- /samples/typescript/getSchema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Get a previously created schema 25 | // description: Gets information about a schema which was previously created in the project. 26 | // usage: node getSchema.js 27 | 28 | // [START pubsub_get_schema] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function getSchema(schemaNameOrId: string) { 41 | const schema = pubSubClient.schema(schemaNameOrId); 42 | const info = await schema.get(); 43 | const fullName = await schema.getName(); 44 | console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`); 45 | } 46 | // [END pubsub_get_schema] 47 | 48 | function main(schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID') { 49 | getSchema(schemaNameOrId).catch(err => { 50 | console.error(err.message); 51 | process.exitCode = 1; 52 | }); 53 | } 54 | 55 | main(...process.argv.slice(2)); 56 | -------------------------------------------------------------------------------- /samples/typescript/getSchemaRevision.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | * This snippet demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Get a previously created schema revision 25 | // description: Gets information about a schema revision which was previously created in the project. 26 | // usage: node getSchemaRevision.js 27 | 28 | // [START pubsub_get_schema_revision] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | // const revisionId = 'YOUR_REVISION_ID'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub} from '@google-cloud/pubsub'; 37 | 38 | // Creates a client; cache this for further use 39 | const pubSubClient = new PubSub(); 40 | 41 | async function getSchemaRevision(schemaNameOrId: string, revisionId: string) { 42 | const schema = pubSubClient.schema(schemaNameOrId); 43 | const name = await schema.getName(); 44 | 45 | // Use the gapic client to delete the schema revision. 46 | const schemaClient = await pubSubClient.getSchemaClient(); 47 | const schemaInfo = await schemaClient.getSchema({ 48 | name: `${name}@${revisionId}`, 49 | }); 50 | 51 | console.log( 52 | `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.`, 53 | ); 54 | } 55 | // [END pubsub_get_schema_revision] 56 | 57 | function main( 58 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 59 | revisionId = 'YOUR_REVISION_ID', 60 | ) { 61 | getSchemaRevision(schemaNameOrId, revisionId).catch(err => { 62 | console.error(err.message); 63 | process.exitCode = 1; 64 | }); 65 | } 66 | 67 | main(...process.argv.slice(2)); 68 | -------------------------------------------------------------------------------- /samples/typescript/getSubscription.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Get Subscription 25 | // description: Gets the metadata for a subscription. 26 | // usage: node getSubscription.js 27 | 28 | /** 29 | * TODO(developer): Uncomment this variable before running the sample. 30 | */ 31 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 32 | 33 | // Imports the Google Cloud client library 34 | import {PubSub} from '@google-cloud/pubsub'; 35 | 36 | // Creates a client; cache this for further use 37 | const pubSubClient = new PubSub(); 38 | 39 | async function getSubscription(subscriptionNameOrId: string) { 40 | // Gets the metadata for the subscription, as google.pubsub.v1.ISubscription 41 | const [metadata] = await pubSubClient 42 | .subscription(subscriptionNameOrId) 43 | .getMetadata(); 44 | 45 | console.log(`Subscription: ${metadata.name}`); 46 | console.log(`Topic: ${metadata.topic}`); 47 | console.log(`Push config: ${metadata.pushConfig?.pushEndpoint}`); 48 | console.log(`Ack deadline: ${metadata.ackDeadlineSeconds}s`); 49 | } 50 | 51 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 52 | getSubscription(subscriptionNameOrId).catch(err => { 53 | console.error(err.message); 54 | process.exitCode = 1; 55 | }); 56 | } 57 | 58 | main(...process.argv.slice(2)); 59 | -------------------------------------------------------------------------------- /samples/typescript/getSubscriptionPolicy.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Get Subscription Policy 25 | // description: Gets the IAM policy for a subscription. 26 | // usage: node getSubscriptionPolicy.js 27 | 28 | // [START pubsub_get_subscription_policy] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub, Policy} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function getSubscriptionPolicy(subscriptionNameOrId: string) { 41 | // Retrieves the IAM policy for the subscription 42 | const [policy]: [Policy] = await pubSubClient 43 | .subscription(subscriptionNameOrId) 44 | .iam.getPolicy(); 45 | 46 | console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`); 47 | } 48 | // [END pubsub_get_subscription_policy] 49 | 50 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 51 | getSubscriptionPolicy(subscriptionNameOrId).catch(err => { 52 | console.error(err.message); 53 | process.exitCode = 1; 54 | }); 55 | } 56 | 57 | main(...process.argv.slice(2)); 58 | -------------------------------------------------------------------------------- /samples/typescript/getTopicPolicy.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | * This sample demonstrates how to perform basic operations on topics with 17 | * the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Get Topic Policy 25 | // description: Gets the IAM policy for a topic. 26 | // usage: node getTopicPolicy.js 27 | 28 | // [START pubsub_get_topic_policy] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub, Policy} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function getTopicPolicy(topicNameOrId: string) { 41 | // Retrieves the IAM policy for the topic 42 | const [policy]: [Policy] = await pubSubClient 43 | .topic(topicNameOrId) 44 | .iam.getPolicy(); 45 | console.log('Policy for topic: %j.', policy.bindings); 46 | } 47 | // [END pubsub_get_topic_policy] 48 | 49 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 50 | getTopicPolicy(topicNameOrId).catch(err => { 51 | console.error(err.message); 52 | process.exitCode = 1; 53 | }); 54 | } 55 | 56 | main(...process.argv.slice(2)); 57 | -------------------------------------------------------------------------------- /samples/typescript/listAllTopics.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | * This sample demonstrates how to perform basic operations on topics with 17 | * the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: List All Topics 25 | // description: Lists all topics in the current project. 26 | // usage: node listAllTopics.js 27 | 28 | // [START pubsub_list_topics] 29 | // Imports the Google Cloud client library 30 | import {PubSub, Topic} from '@google-cloud/pubsub'; 31 | 32 | // Creates a client; cache this for further use 33 | const pubSubClient = new PubSub(); 34 | 35 | async function listAllTopics() { 36 | // Lists all topics in the current project 37 | const [topics] = await pubSubClient.getTopics(); 38 | console.log('Topics:'); 39 | topics.forEach((topic: Topic) => console.log(topic.name)); 40 | } 41 | // [END pubsub_list_topics] 42 | 43 | function main() { 44 | listAllTopics().catch(err => { 45 | console.error(err.message); 46 | process.exitCode = 1; 47 | }); 48 | } 49 | 50 | main(); 51 | -------------------------------------------------------------------------------- /samples/typescript/listSchemaRevisions.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: List Revisions on a Schema 25 | // description: Gets a list of revisions on a schema which was previously created in the project. 26 | // usage: node listSchemaRevisions.js 27 | 28 | // [START pubsub_list_schema_revisions] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function listSchemaRevisions(schemaNameOrId: string) { 41 | // Get the fully qualified schema name. 42 | const schema = pubSubClient.schema(schemaNameOrId); 43 | const name = await schema.getName(); 44 | 45 | // Use the gapic client to list the schema revisions. 46 | const schemaClient = await pubSubClient.getSchemaClient(); 47 | const [results] = await schemaClient.listSchemaRevisions({ 48 | name, 49 | }); 50 | for (const rev of results) { 51 | console.log(rev.revisionId, rev.revisionCreateTime); 52 | } 53 | console.log(`Listed revisions of schema ${name}.`); 54 | } 55 | // [END pubsub_list_schema_revisions] 56 | 57 | function main(schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID') { 58 | listSchemaRevisions(schemaNameOrId).catch(err => { 59 | console.error(err.message); 60 | process.exitCode = 1; 61 | }); 62 | } 63 | 64 | main(...process.argv.slice(2)); 65 | -------------------------------------------------------------------------------- /samples/typescript/listSchemas.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: List schemas on a project 25 | // description: Gets a list of schemas which were previously created in the project. 26 | // usage: node listSchemas.js 27 | 28 | // [START pubsub_list_schemas] 29 | 30 | // Imports the Google Cloud client library 31 | import {PubSub} from '@google-cloud/pubsub'; 32 | 33 | // Creates a client; cache this for further use 34 | const pubSubClient = new PubSub(); 35 | 36 | async function listSchemas() { 37 | for await (const s of pubSubClient.listSchemas()) { 38 | console.log(s.name); 39 | } 40 | console.log('Listed schemas.'); 41 | } 42 | // [END pubsub_list_schemas] 43 | 44 | function main() { 45 | listSchemas().catch(err => { 46 | console.error(err.message); 47 | process.exitCode = 1; 48 | }); 49 | } 50 | 51 | main(); 52 | -------------------------------------------------------------------------------- /samples/typescript/listSubscriptions.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: List Subscriptions 25 | // description: Lists all subscriptions in the current project. 26 | // usage: node listSubscriptions.js 27 | 28 | // [START pubsub_list_subscriptions] 29 | // Imports the Google Cloud client library 30 | import {PubSub, Subscription} from '@google-cloud/pubsub'; 31 | 32 | // Creates a client; cache this for further use 33 | const pubSubClient = new PubSub(); 34 | 35 | async function listSubscriptions() { 36 | // Lists all subscriptions in the current project 37 | const [subscriptions] = await pubSubClient.getSubscriptions(); 38 | console.log('Subscriptions:'); 39 | subscriptions.forEach((subscription: Subscription) => 40 | console.log(subscription.name), 41 | ); 42 | } 43 | // [END pubsub_list_subscriptions] 44 | 45 | function main() { 46 | listSubscriptions().catch(console.error); 47 | } 48 | 49 | main(); 50 | -------------------------------------------------------------------------------- /samples/typescript/listTopicSubscriptions.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: List Subscriptions On a Topic 25 | // description: Lists all subscriptions in the current project, filtering by a topic. 26 | // usage: node listTopicSubscriptions.js 27 | 28 | // [START pubsub_list_topic_subscriptions] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub, Subscription} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function listTopicSubscriptions(topicNameOrId: string) { 41 | // Lists all subscriptions for the topic 42 | const [subscriptions] = await pubSubClient 43 | .topic(topicNameOrId) 44 | .getSubscriptions(); 45 | 46 | console.log(`Subscriptions for ${topicNameOrId}:`); 47 | subscriptions.forEach((subscription: Subscription) => 48 | console.log(subscription.name), 49 | ); 50 | } 51 | // [END pubsub_list_topic_subscriptions] 52 | 53 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 54 | listTopicSubscriptions(topicNameOrId).catch(err => { 55 | console.error(err.message); 56 | process.exitCode = 1; 57 | }); 58 | } 59 | 60 | main(...process.argv.slice(2)); 61 | -------------------------------------------------------------------------------- /samples/typescript/quickstart.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2023 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 | // http://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 | /* eslint-disable n/no-process-exit */ 16 | 17 | // sample-metadata: 18 | // title: Quickstart 19 | // description: A quick introduction to using the Pub/Sub client library. 20 | // usage: node quickstart.js 21 | 22 | // [START pubsub_quickstart_create_topic] 23 | // Imports the Google Cloud client library 24 | import {PubSub} from '@google-cloud/pubsub'; 25 | 26 | async function quickstart( 27 | projectId = 'your-project-id', // Your Google Cloud Platform project ID 28 | topicNameOrId = 'my-topic', // Name for the new topic to create 29 | subscriptionName = 'my-sub', // Name for the new subscription to create 30 | ) { 31 | // Instantiates a client 32 | const pubsub = new PubSub({projectId}); 33 | 34 | // Creates a new topic 35 | const [topic] = await pubsub.createTopic(topicNameOrId); 36 | console.log(`Topic ${topic.name} created.`); 37 | 38 | // Creates a subscription on that new topic 39 | const [subscription] = await topic.createSubscription(subscriptionName); 40 | 41 | // Receive callbacks for new messages on the subscription 42 | subscription.on('message', message => { 43 | console.log('Received message:', message.data.toString()); 44 | process.exit(0); 45 | }); 46 | 47 | // Receive callbacks for errors on the subscription 48 | subscription.on('error', error => { 49 | console.error('Received error:', error); 50 | process.exit(1); 51 | }); 52 | 53 | // Send a message to the topic 54 | await topic.publishMessage({data: Buffer.from('Test message!')}); 55 | } 56 | // [END pubsub_quickstart_create_topic] 57 | 58 | quickstart(...process.argv.slice(2)).catch(err => { 59 | console.error(err.message); 60 | process.exitCode = 1; 61 | }); 62 | -------------------------------------------------------------------------------- /samples/typescript/removeDeadLetterPolicy.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2020-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Remove Dead Letter Policy 25 | // description: Remove Dead Letter Policy from subscription. 26 | // usage: node removeDeadLetterPolicy.js 27 | 28 | // [START pubsub_dead_letter_remove] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub, SubscriptionMetadata} from '@google-cloud/pubsub'; 37 | 38 | // Creates a client; cache this for further use 39 | const pubSubClient = new PubSub(); 40 | 41 | async function removeDeadLetterPolicy( 42 | topicNameOrId: string, 43 | subscriptionNameOrId: string, 44 | ) { 45 | const metadata: SubscriptionMetadata = { 46 | deadLetterPolicy: null, 47 | }; 48 | 49 | await pubSubClient 50 | .topic(topicNameOrId) 51 | .subscription(subscriptionNameOrId) 52 | .setMetadata(metadata); 53 | 54 | console.log( 55 | `Removed dead letter topic from ${subscriptionNameOrId} subscription.`, 56 | ); 57 | } 58 | // [END pubsub_dead_letter_remove] 59 | 60 | function main( 61 | topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', 62 | subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', 63 | ) { 64 | removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { 65 | console.error(err.message); 66 | process.exitCode = 1; 67 | }); 68 | } 69 | 70 | main(...process.argv.slice(2)); 71 | -------------------------------------------------------------------------------- /samples/typescript/rollbackSchema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * schemas with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Rollback a Schema 25 | // description: Rolls back a schema on a project 26 | // usage: node rollbackSchema.js 27 | 28 | // [START pubsub_rollback_schema] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID'; 33 | // const revisionId = 'YOUR_REVISION_ID'; 34 | 35 | // Imports the Google Cloud client library 36 | import {PubSub} from '@google-cloud/pubsub'; 37 | 38 | // Creates a client; cache this for further use 39 | const pubSubClient = new PubSub(); 40 | 41 | async function rollbackSchema(schemaNameOrId: string, revisionId: string) { 42 | // Get the fully qualified schema name. 43 | const schema = pubSubClient.schema(schemaNameOrId); 44 | const name = await schema.getName(); 45 | 46 | // Use the gapic client to roll back the schema revision. 47 | const schemaClient = await pubSubClient.getSchemaClient(); 48 | await schemaClient.rollbackSchema({ 49 | name, 50 | revisionId, 51 | }); 52 | 53 | console.log(`Schema ${name} revision ${revisionId} rolled back.`); 54 | } 55 | // [END pubsub_rollback_schema] 56 | 57 | function main( 58 | schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', 59 | revisionId = 'YOUR_REVISION_ID', 60 | ) { 61 | rollbackSchema(schemaNameOrId, revisionId).catch(err => { 62 | console.error(err.message); 63 | process.exitCode = 1; 64 | }); 65 | } 66 | 67 | main(...process.argv.slice(2)); 68 | -------------------------------------------------------------------------------- /samples/typescript/setTopicPolicy.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | * This sample demonstrates how to perform basic operations on topics with 17 | * the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Set Topic IAM Policy 25 | // description: Sets the IAM policy for a topic. 26 | // usage: node setTopicPolicy.js 27 | 28 | // [START pubsub_set_topic_policy] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub, Policy} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function setTopicPolicy(topicNameOrId: string) { 41 | // The new IAM policy 42 | const newPolicy: Policy = { 43 | bindings: [ 44 | { 45 | // Add a group as editors 46 | role: 'roles/pubsub.editor', 47 | members: ['group:cloud-logs@google.com'], 48 | }, 49 | { 50 | // Add all users as viewers 51 | role: 'roles/pubsub.viewer', 52 | members: ['allUsers'], 53 | }, 54 | ], 55 | }; 56 | 57 | // Updates the IAM policy for the topic 58 | const [updatedPolicy] = await pubSubClient 59 | .topic(topicNameOrId) 60 | .iam.setPolicy(newPolicy); 61 | console.log('Updated policy for topic: %j', updatedPolicy.bindings); 62 | } 63 | // [END pubsub_set_topic_policy] 64 | 65 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 66 | setTopicPolicy(topicNameOrId).catch(err => { 67 | console.error(err.message); 68 | process.exitCode = 1; 69 | }); 70 | } 71 | 72 | main(...process.argv.slice(2)); 73 | -------------------------------------------------------------------------------- /samples/typescript/testSubscriptionPermissions.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Test Subscription Permissions 25 | // description: Tests the permissions for a subscription. 26 | // usage: node testSubscriptionPermissions.js 27 | 28 | // [START pubsub_test_subscription_permissions] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function testSubscriptionPermissions(subscriptionNameOrId: string) { 41 | const permissionsToTest = [ 42 | 'pubsub.subscriptions.consume', 43 | 'pubsub.subscriptions.update', 44 | ]; 45 | 46 | // Tests the IAM policy for the specified subscription 47 | const [permissions] = await pubSubClient 48 | .subscription(subscriptionNameOrId) 49 | .iam.testPermissions(permissionsToTest); 50 | 51 | console.log('Tested permissions for subscription: %j', permissions); 52 | } 53 | // [END pubsub_test_subscription_permissions] 54 | 55 | function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { 56 | testSubscriptionPermissions(subscriptionNameOrId).catch(err => { 57 | console.error(err.message); 58 | process.exitCode = 1; 59 | }); 60 | } 61 | 62 | main(...process.argv.slice(2)); 63 | -------------------------------------------------------------------------------- /samples/typescript/testTopicPermissions.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 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 | * This sample demonstrates how to perform basic operations on topics with 17 | * the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Test Topic Permissions 25 | // description: Tests the permissions for a topic. 26 | // usage: node testTopicPermissions.js 27 | 28 | // [START pubsub_test_topic_permissions] 29 | /** 30 | * TODO(developer): Uncomment this variable before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | 34 | // Imports the Google Cloud client library 35 | import {PubSub} from '@google-cloud/pubsub'; 36 | 37 | // Creates a client; cache this for further use 38 | const pubSubClient = new PubSub(); 39 | 40 | async function testTopicPermissions(topicNameOrId: string) { 41 | const permissionsToTest = [ 42 | 'pubsub.topics.attachSubscription', 43 | 'pubsub.topics.publish', 44 | 'pubsub.topics.update', 45 | ]; 46 | 47 | // Tests the IAM policy for the specified topic 48 | const [permissions] = await pubSubClient 49 | .topic(topicNameOrId) 50 | .iam.testPermissions(permissionsToTest); 51 | 52 | console.log('Tested permissions for topic: %j', permissions); 53 | } 54 | // [END pubsub_test_topic_permissions] 55 | 56 | function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { 57 | testTopicPermissions(topicNameOrId).catch(err => { 58 | console.error(err.message); 59 | process.exitCode = 1; 60 | }); 61 | } 62 | 63 | main(...process.argv.slice(2)); 64 | -------------------------------------------------------------------------------- /samples/typescript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": "..", 5 | "outDir": "../build", 6 | "resolveJsonModule": true, 7 | "lib": [ 8 | "es2018", 9 | "dom" 10 | ], 11 | "module": "es2020", 12 | "sourceMap": false, 13 | "moduleResolution": "node" 14 | }, 15 | "include": [ 16 | "./*.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /samples/typescript/updateTopicSchema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2024 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 | // http://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 | * This application demonstrates how to perform basic operations on 17 | * subscriptions with the Google Cloud Pub/Sub API. 18 | * 19 | * For more information, see the README.md under /pubsub and the documentation 20 | * at https://cloud.google.com/pubsub/docs. 21 | */ 22 | 23 | // sample-metadata: 24 | // title: Update Topic Schema 25 | // description: Update the schema on a topic. 26 | // usage: node updateTopicSchema.js 27 | 28 | // [START pubsub_update_topic_schema] 29 | /** 30 | * TODO(developer): Uncomment these variables before running the sample. 31 | */ 32 | // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; 33 | // const firstRevisionId = 'YOUR_REVISION_ID'; 34 | // const lastRevisionId = 'YOUR_REVISION_ID'; 35 | 36 | // Imports the Google Cloud client library 37 | import {PubSub, TopicMetadata} from '@google-cloud/pubsub'; 38 | 39 | // Creates a client; cache this for further use 40 | const pubSubClient = new PubSub(); 41 | 42 | async function updateTopicSchema( 43 | topicNameOrId: string, 44 | firstRevisionId: string, 45 | lastRevisionId: string, 46 | ) { 47 | const metadata: TopicMetadata = { 48 | schemaSettings: { 49 | firstRevisionId, 50 | lastRevisionId, 51 | }, 52 | }; 53 | 54 | await pubSubClient.topic(topicNameOrId).setMetadata(metadata); 55 | 56 | console.log('Schema metadata updated successfully.'); 57 | } 58 | // [END pubsub_update_topic_schema] 59 | 60 | function main( 61 | topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', 62 | firstRevisionId = 'YOUR_REVISION_ID', 63 | lastRevisionId = 'YOUR_REVISION_ID', 64 | ) { 65 | updateTopicSchema(topicNameOrId, firstRevisionId, lastRevisionId).catch( 66 | err => { 67 | console.error(err.message); 68 | process.exitCode = 1; 69 | }, 70 | ); 71 | } 72 | 73 | main(...process.argv.slice(2)); 74 | -------------------------------------------------------------------------------- /src/debug.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2023 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 | // http://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 | * Represents a debug message the user might want to print out for logging 17 | * while debugging or whatnot. These will always come by way of the 'error' 18 | * channel on streams or other event emitters. It's completely fine to 19 | * ignore them, as some will just be verbose logging info, but they may 20 | * help figure out what's going wrong. Support may also ask you to catch 21 | * these channels, which you can do like so: 22 | * 23 | * ``` 24 | * subscription.on('debug', msg => console.log(msg.message)); 25 | * ``` 26 | * 27 | * These values are _not_ guaranteed to remain stable, even within a major 28 | * version, so don't depend on them for your program logic. Debug outputs 29 | * may be added or removed at any time, without warning. 30 | */ 31 | export class DebugMessage { 32 | constructor( 33 | public message: string, 34 | public error?: Error, 35 | ) {} 36 | } 37 | -------------------------------------------------------------------------------- /src/default-options.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {Duration} from './temporal'; 18 | 19 | // These options will be used library-wide. They're specified here so that 20 | // they can be changed easily in the future. 21 | export const defaultOptions = { 22 | subscription: { 23 | // The maximum number of messages that may be queued for receiving, 24 | // with the default lease manager. 25 | maxOutstandingMessages: 1000, 26 | 27 | // The maximum amount of message data that may be queued for receiving, 28 | // in bytes, with the default lease manager. 29 | maxOutstandingBytes: 100 * 1024 * 1024, 30 | 31 | // The minimum length of time a message's lease will be extended by. 32 | minAckDeadline: undefined, 33 | 34 | // The maximum length of time a message's lease will be extended by. 35 | maxAckDeadline: Duration.from({minutes: 10}), 36 | 37 | // The maximum amount of time that a message's lease will ever 38 | // be extended. 39 | maxExtensionTime: Duration.from({minutes: 60}), 40 | 41 | // The maximum number of subscription streams/threads that will ever 42 | // be opened. 43 | maxStreams: 5, 44 | 45 | // The starting number of seconds that ack deadlines will be extended. 46 | startingAckDeadline: Duration.from({seconds: 10}), 47 | }, 48 | 49 | publish: { 50 | // The maximum number of messages we'll batch up for publish(). 51 | maxOutstandingMessages: 100, 52 | 53 | // The maximum size of the total batched up messages for publish(). 54 | maxOutstandingBytes: 1 * 1024 * 1024, 55 | 56 | // The maximum time we'll wait to send batched messages, in milliseconds. 57 | maxDelayMillis: 10, 58 | }, 59 | }; 60 | -------------------------------------------------------------------------------- /src/histogram.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export interface HistogramOptions { 18 | min?: number; 19 | max?: number; 20 | } 21 | 22 | /*! 23 | * The Histogram class is used to capture the lifespan of messages within the 24 | * the client. These durations are then used to calculate the 99th percentile 25 | * of ack deadlines for future messages. 26 | * 27 | * @private 28 | * @class 29 | */ 30 | export class Histogram { 31 | options: HistogramOptions; 32 | data: Map; 33 | length: number; 34 | constructor(options?: HistogramOptions) { 35 | this.options = Object.assign( 36 | {min: 0, max: Number.MAX_SAFE_INTEGER}, 37 | options, 38 | ); 39 | this.data = new Map(); 40 | this.length = 0; 41 | } 42 | /*! 43 | * Adds a value to the histogram. 44 | * 45 | * @private 46 | * @param {numnber} value - The value in milliseconds. 47 | */ 48 | add(value: number): void { 49 | value = Math.ceil(value); 50 | value = Math.max(value, this.options.min!); 51 | value = Math.min(value, this.options.max!); 52 | if (!this.data.has(value)) { 53 | this.data.set(value, 0); 54 | } 55 | const count = this.data.get(value)!; 56 | this.data.set(value, count + 1); 57 | this.length += 1; 58 | } 59 | /*! 60 | * Retrieves the nth percentile of recorded values. 61 | * 62 | * @private 63 | * @param {number} percent The requested percentage. 64 | * @return {number} 65 | */ 66 | percentile(percent: number): number { 67 | percent = Math.min(percent, 100); 68 | let target = this.length - this.length * (percent / 100); 69 | const keys = Array.from(this.data.keys()); 70 | let key; 71 | for (let i = keys.length - 1; i > -1; i--) { 72 | key = keys[i]; 73 | target -= this.data.get(key)!; 74 | if (target <= 0) { 75 | return key; 76 | } 77 | } 78 | return this.options.min!; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/publisher/publish-error.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import {grpc} from 'google-gax'; 17 | 18 | /** 19 | * Exception to be thrown during failed ordered publish. 20 | * 21 | * @class 22 | * @extends Error 23 | */ 24 | export class PublishError extends Error implements grpc.ServiceError { 25 | code: grpc.status; 26 | details: string; 27 | metadata: grpc.Metadata; 28 | orderingKey: string; 29 | error: grpc.ServiceError; 30 | constructor(key: string, err: grpc.ServiceError) { 31 | super(`Unable to publish for key "${key}". Reason: ${err.message}`); 32 | 33 | /** 34 | * The gRPC grpc.status code. 35 | * 36 | * @name PublishError#code 37 | * @type {number} 38 | */ 39 | this.code = err.code; 40 | 41 | /** 42 | * The gRPC grpc.status details. 43 | * 44 | * @name PublishError#details 45 | * @type {string} 46 | */ 47 | this.details = err.details; 48 | 49 | /** 50 | * The gRPC grpc.Metadata object. 51 | * 52 | * @name PublishError#grpc.Metadata 53 | * @type {object} 54 | */ 55 | this.metadata = err.metadata; 56 | 57 | /** 58 | * The ordering key this failure occurred for. 59 | * 60 | * @name PublishError#orderingKey 61 | * @type {string} 62 | */ 63 | this.orderingKey = key; 64 | 65 | /** 66 | * The original gRPC error. 67 | * 68 | * @name PublishError#error 69 | * @type {Error} 70 | */ 71 | this.error = err; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/pull-retry.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import {grpc} from 'google-gax'; 17 | 18 | /*! 19 | * retryable grpc.status codes 20 | */ 21 | export const RETRY_CODES: grpc.status[] = [ 22 | grpc.status.DEADLINE_EXCEEDED, 23 | grpc.status.RESOURCE_EXHAUSTED, 24 | grpc.status.ABORTED, 25 | grpc.status.INTERNAL, 26 | grpc.status.UNAVAILABLE, 27 | grpc.status.CANCELLED, 28 | ]; 29 | 30 | /** 31 | * Used to track pull requests and determine if additional requests should be 32 | * made, etc. 33 | * 34 | * @class 35 | * @private 36 | */ 37 | export class PullRetry { 38 | /** 39 | * Determines if a request grpc.status should be retried. 40 | * 41 | * Deadlines behave kind of unexpectedly on streams, rather than using it as 42 | * an indicator of when to give up trying to connect, it actually dictates 43 | * how long the stream should stay open. Because of this, it is virtually 44 | * impossible to determine whether or not a deadline error is the result of 45 | * the server closing the stream or if we timed out waiting for a connection. 46 | * 47 | * @private 48 | * @param {object} grpc.status The request grpc.status. 49 | * @returns {boolean} 50 | */ 51 | static retry(err: grpc.StatusObject): boolean { 52 | if ( 53 | err.code === grpc.status.UNAVAILABLE && 54 | err.details && 55 | err.details.match(/Server shutdownNow invoked/) 56 | ) { 57 | return true; 58 | } 59 | 60 | return RETRY_CODES.includes(err.code); 61 | } 62 | 63 | static resetFailures(err: grpc.StatusObject): boolean { 64 | return ( 65 | err.code === grpc.status.OK || err.code === grpc.status.DEADLINE_EXCEEDED 66 | ); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/v1/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2025 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 | // ** This file is automatically generated by gapic-generator-typescript. ** 16 | // ** https://github.com/googleapis/gapic-generator-typescript ** 17 | // ** All changes to this file may be overwritten. ** 18 | 19 | export {PublisherClient} from './publisher_client'; 20 | export {SchemaServiceClient} from './schema_service_client'; 21 | export {SubscriberClient} from './subscriber_client'; 22 | -------------------------------------------------------------------------------- /src/v1/publisher_proto_list.json: -------------------------------------------------------------------------------- 1 | [ 2 | "../../protos/google/pubsub/v1/pubsub.proto", 3 | "../../protos/google/pubsub/v1/schema.proto" 4 | ] 5 | -------------------------------------------------------------------------------- /src/v1/schema_service_proto_list.json: -------------------------------------------------------------------------------- 1 | [ 2 | "../../protos/google/pubsub/v1/pubsub.proto", 3 | "../../protos/google/pubsub/v1/schema.proto" 4 | ] 5 | -------------------------------------------------------------------------------- /src/v1/subscriber_proto_list.json: -------------------------------------------------------------------------------- 1 | [ 2 | "../../protos/google/pubsub/v1/pubsub.proto", 3 | "../../protos/google/pubsub/v1/schema.proto" 4 | ] 5 | -------------------------------------------------------------------------------- /system-test/fixtures/province.json: -------------------------------------------------------------------------------- 1 | {"name":"Ontario","post_abbr":"ON"} -------------------------------------------------------------------------------- /system-test/fixtures/provinces.avsc: -------------------------------------------------------------------------------- 1 | { 2 | "type":"record", 3 | "name":"Province", 4 | "namespace":"utilities", 5 | "doc":"A list of provinces in Canada.", 6 | "fields":[ 7 | { 8 | "name":"name", 9 | "type":"string", 10 | "doc":"The common name of the province." 11 | }, 12 | { 13 | "name":"post_abbr", 14 | "type":"string", 15 | "doc":"The postal code abbreviation of the province." 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /system-test/fixtures/sample/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pubsub-sample-fixture", 3 | "description": "An app we're using to test the library.", 4 | "scripts": { 5 | "check": "gts check", 6 | "clean": "gts clean", 7 | "compile": "tsc -p .", 8 | "fix": "gts fix", 9 | "prepare": "npm run compile", 10 | "pretest": "npm run compile", 11 | "posttest": "npm run check", 12 | "start": "node build/src/index.js" 13 | }, 14 | "license": "Apache-2.0", 15 | "dependencies": { 16 | "@google-cloud/pubsub": "file:./pubsub.tgz" 17 | }, 18 | "devDependencies": { 19 | "@types/node": "^22.0.0", 20 | "typescript": "^5.1.6", 21 | "gts": "^6.0.0" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /system-test/fixtures/sample/src/index.ts: -------------------------------------------------------------------------------- 1 | import {PubSub} from '@google-cloud/pubsub'; 2 | 3 | async function main() { 4 | const pubsub = new PubSub(); 5 | console.log(pubsub); 6 | } 7 | 8 | main(); 9 | -------------------------------------------------------------------------------- /system-test/fixtures/sample/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "build", 6 | "types": ["node"], 7 | "skipLibCheck": false, 8 | }, 9 | "include": [ 10 | "src/*.ts" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /system-test/install.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | // http://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 | import * as execa from 'execa'; 16 | import * as mv from 'mv'; 17 | import {ncp} from 'ncp'; 18 | import * as tmp from 'tmp'; 19 | import {promisify} from 'util'; 20 | import {describe, it, after} from 'mocha'; 21 | 22 | const keep = false; 23 | const mvp = promisify(mv) as {} as (...args: string[]) => Promise; 24 | const ncpp = promisify(ncp); 25 | const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); 26 | const stagingPath = stagingDir.name; 27 | // eslint-disable-next-line @typescript-eslint/no-var-requires 28 | const pkg = require('../../package.json'); 29 | 30 | describe('📦 pack and install', () => { 31 | /** 32 | * Create a staging directory with temp fixtures used to test on a fresh 33 | * application. 34 | */ 35 | it('should be able to use the d.ts', async () => { 36 | await execa('npm', ['pack', '--unsafe-perm']); 37 | const tarball = `google-cloud-pubsub-${pkg.version}.tgz`; 38 | await mvp(tarball, `${stagingPath}/pubsub.tgz`); 39 | await ncpp('system-test/fixtures/sample', `${stagingPath}/`); 40 | await execa('npm', ['install', '--unsafe-perm'], { 41 | cwd: `${stagingPath}/`, 42 | stdio: 'inherit', 43 | }); 44 | await execa('node', ['--throw-deprecation', 'build/src/index.js'], { 45 | cwd: `${stagingPath}/`, 46 | stdio: 'inherit', 47 | }); 48 | }); 49 | 50 | /** 51 | * CLEAN UP - remove the staging directory when done. 52 | */ 53 | after('cleanup staging', () => { 54 | if (!keep) { 55 | stagingDir.removeCallback(); 56 | } 57 | }); 58 | }); 59 | -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 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 | // http://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 | import * as assert from 'assert'; 16 | import {describe, it} from 'mocha'; 17 | import * as pubsub from '../src'; 18 | 19 | describe('exports', () => { 20 | it('should export the gapic clients', () => { 21 | assert.ok(pubsub.v1); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /test/publisher/publish-error.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2019 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as assert from 'assert'; 18 | import {describe, it, beforeEach} from 'mocha'; 19 | import {grpc} from 'google-gax'; 20 | import {PublishError} from '../../src/publisher/publish-error'; 21 | 22 | describe('PublishError', () => { 23 | let error: PublishError; 24 | 25 | const orderingKey = 'abcd'; 26 | const fakeError = new Error('Oh noes') as grpc.ServiceError; 27 | 28 | fakeError.code = 1; 29 | fakeError.details = 'Something went wrong!'; 30 | fakeError.metadata = new grpc.Metadata(); 31 | 32 | beforeEach(() => { 33 | error = new PublishError(orderingKey, fakeError); 34 | }); 35 | 36 | it('should give a helpful message', () => { 37 | assert.strictEqual( 38 | error.message, 39 | `Unable to publish for key "${orderingKey}". Reason: ${fakeError.message}`, 40 | ); 41 | }); 42 | 43 | it('should capture the error code', () => { 44 | assert.strictEqual(error.code, fakeError.code); 45 | }); 46 | 47 | it('should capture the error details', () => { 48 | assert.strictEqual(error.details, fakeError.details); 49 | }); 50 | 51 | it('should capture the error metadata', () => { 52 | assert.strictEqual(error.metadata, fakeError.metadata); 53 | }); 54 | 55 | it('should capture the ordering key', () => { 56 | assert.strictEqual(error.orderingKey, orderingKey); 57 | }); 58 | 59 | it('should capture the original error', () => { 60 | assert.strictEqual(error.error, fakeError); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /test/temporal.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2022 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 | // http://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 | import {describe, it} from 'mocha'; 16 | import {Duration} from '../src/temporal'; 17 | import * as assert from 'assert'; 18 | 19 | describe('temporal', () => { 20 | describe('Duration', () => { 21 | it('can be created from millis', () => { 22 | const duration = Duration.from({millis: 1234}); 23 | assert.strictEqual(duration.totalOf('second'), 1.234); 24 | }); 25 | it('can be created from seconds', () => { 26 | const duration = Duration.from({seconds: 1.234}); 27 | assert.strictEqual(duration.totalOf('millisecond'), 1234); 28 | }); 29 | it('can be created from minutes', () => { 30 | const duration = Duration.from({minutes: 30}); 31 | assert.strictEqual(duration.totalOf('hour'), 0.5); 32 | }); 33 | it('can be created from hours', () => { 34 | const duration = Duration.from({hours: 1.5}); 35 | assert.strictEqual(duration.totalOf('minute'), 90); 36 | }); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /test/test-utils.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2025 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 | // http://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 | import {SinonSandbox, SinonFakeTimers} from 'sinon'; 16 | 17 | type FakeTimersParam = Parameters[0]; 18 | interface FakeTimerConfig { 19 | now?: number; 20 | toFake?: string[]; 21 | } 22 | 23 | /** 24 | * Utilities for unit test code. 25 | * 26 | * @private 27 | */ 28 | export class TestUtils { 29 | /** 30 | * This helper should be used to enable fake timers for Sinon sandbox. 31 | * 32 | * @param sandbox The sandbox 33 | * @param now An optional date to set for "now" 34 | * @returns The clock object from useFakeTimers() 35 | */ 36 | static useFakeTimers(sandbox: SinonSandbox, now?: number): SinonFakeTimers { 37 | const config: FakeTimerConfig = { 38 | toFake: [ 39 | 'setTimeout', 40 | 'clearTimeout', 41 | 'setInterval', 42 | 'clearInterval', 43 | 'Date', 44 | ], 45 | }; 46 | if (now) { 47 | config.now = now; 48 | } 49 | 50 | // The types are screwy in useFakeTimers(). I'm just going to pick one. 51 | return sandbox.useFakeTimers(config as FakeTimersParam); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /test/tracing.ts: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2021 Google LLC. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { 18 | BasicTracerProvider, 19 | InMemorySpanExporter, 20 | SimpleSpanProcessor, 21 | } from '@opentelemetry/sdk-trace-base'; 22 | 23 | /** 24 | * This file is used to initialise a global tracing provider and span exporter 25 | * for our tests used in our project. This was the only way I was able to get 26 | * the tracing tests to work. 27 | * 28 | * Now before each test related or touches Opentelemetry 29 | * we are resetting the exporter defined below to ensure there are no spans 30 | * from previous tests still in memory. This is achived by calling `reset` 31 | * on the exporter in the unit tests while keeping one instance of 32 | * the trace provider and exporter. 33 | * 34 | * The tracing provider is being registered as a global trace provider before 35 | * we are importing our actual code which uses the Opentelemetry API to ensure 36 | * its defined beforehand. 37 | */ 38 | export const exporter: InMemorySpanExporter = new InMemorySpanExporter(); 39 | export const provider: BasicTracerProvider = new BasicTracerProvider(); 40 | provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); 41 | provider.register(); 42 | -------------------------------------------------------------------------------- /test/util.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2022 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 | // http://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 | import {describe, it} from 'mocha'; 16 | import {addToBucket, Throttler} from '../src/util'; 17 | import * as assert from 'assert'; 18 | 19 | describe('utils', () => { 20 | describe('Throttler', () => { 21 | it('does not allow too many calls through at once', () => { 22 | const throttler = new Throttler(300); 23 | let totalCalls = ''; 24 | 25 | // This one should succeed. 26 | throttler.doMaybe(() => { 27 | totalCalls += 'FIRST'; 28 | }); 29 | 30 | // This one should fail. 31 | throttler.doMaybe(() => { 32 | totalCalls += 'SECOND'; 33 | }); 34 | 35 | // Simulate time passing. 36 | throttler.lastTime! -= 1000; 37 | 38 | // This one should succeed. 39 | throttler.doMaybe(() => { 40 | totalCalls += 'THIRD'; 41 | }); 42 | 43 | assert.strictEqual(totalCalls, 'FIRSTTHIRD'); 44 | }); 45 | }); 46 | 47 | describe('addToBucket', () => { 48 | it('adds to a non-existent bucket', () => { 49 | const map = new Map(); 50 | addToBucket(map, 'a', 'b'); 51 | assert.deepStrictEqual(map.get('a'), ['b']); 52 | }); 53 | 54 | it('adds to an existent bucket', () => { 55 | const map = new Map(); 56 | map.set('a', ['c']); 57 | addToBucket(map, 'a', 'b'); 58 | assert.deepStrictEqual(map.get('a'), ['c', 'b']); 59 | }); 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "build", 6 | "resolveJsonModule": true, 7 | "lib": [ 8 | "es2018", 9 | "dom" 10 | ] 11 | }, 12 | "include": [ 13 | "src/*.ts", 14 | "src/**/*.ts", 15 | "src/v1/*.json", 16 | "test/*.ts", 17 | "test/**/*.ts", 18 | "system-test/*.ts", 19 | "protos/**/*.json" 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | // Copyright 2021 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 | const path = require('path'); 16 | 17 | module.exports = { 18 | entry: './src/index.ts', 19 | output: { 20 | library: 'pubsub', 21 | filename: './pubsub.js', 22 | }, 23 | node: { 24 | child_process: 'empty', 25 | fs: 'empty', 26 | crypto: 'empty', 27 | }, 28 | resolve: { 29 | alias: { 30 | '../../../package.json': path.resolve(__dirname, 'package.json'), 31 | }, 32 | extensions: ['.js', '.json', '.ts'], 33 | }, 34 | module: { 35 | rules: [ 36 | { 37 | test: /\.tsx?$/, 38 | use: 'ts-loader', 39 | exclude: /node_modules/, 40 | }, 41 | { 42 | test: /node_modules[\\/]@grpc[\\/]grpc-js/, 43 | use: 'null-loader', 44 | }, 45 | { 46 | test: /node_modules[\\/]grpc/, 47 | use: 'null-loader', 48 | }, 49 | { 50 | test: /node_modules[\\/]retry-request/, 51 | use: 'null-loader', 52 | }, 53 | { 54 | test: /node_modules[\\/]https?-proxy-agent/, 55 | use: 'null-loader', 56 | }, 57 | { 58 | test: /node_modules[\\/]gtoken/, 59 | use: 'null-loader', 60 | }, 61 | ], 62 | }, 63 | mode: 'production', 64 | }; 65 | --------------------------------------------------------------------------------