diff --git a/.eslintignore b/.eslintignore index cfc348ec4..88856452d 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,3 +5,4 @@ docs/ protos/ system-test/ samples/generated/ +samples/typescript/ diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 24943e116..f06f99a38 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,4 @@ -# Copyright 2024 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest - digest: sha256:609822e3c09b7a1bd90b99655904609f162cc15acb4704f1edf778284c36f429 -# created: 2024-10-01T19:34:30.797530443Z + digest: sha256:c7e4968cfc97a204a4b2381f3ecb55cabc40c4cccf88b1ef8bef0d976be87fee diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index d4ca94189..339b88a21 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1 +1,2 @@ enabled: true +multiScmName: nodejs-pubsub \ No newline at end of file diff --git a/.github/scripts/close-invalid-link.cjs b/.github/scripts/close-invalid-link.cjs index d7a3688e7..fdb514881 100644 --- a/.github/scripts/close-invalid-link.cjs +++ b/.github/scripts/close-invalid-link.cjs @@ -12,21 +12,26 @@ // See the License for the specific language governing permissions and // limitations under the License. +const fs = require('fs'); +const yaml = require('js-yaml'); +const path = require('path'); +const TEMPLATE_FILE_PATH = path.resolve(__dirname, '../ISSUE_TEMPLATE/bug_report.yml') + async function closeIssue(github, owner, repo, number) { await github.rest.issues.createComment({ owner: owner, repo: repo, issue_number: number, - body: 'Issue was opened with an invalid reproduction link. Please make sure the repository is a valid, publicly-accessible github repository, and make sure the url is complete (example: https://github.com/googleapis/google-cloud-node)' + body: "Issue was opened with an invalid reproduction link. Please make sure the repository is a valid, publicly-accessible github repository, and make sure the url is complete (example: https://github.com/googleapis/google-cloud-node)" }); await github.rest.issues.update({ owner: owner, repo: repo, issue_number: number, - state: 'closed' + state: "closed" }); } -module.exports = async ({github, context}) => { +module.exports = async ({ github, context }) => { const owner = context.repo.owner; const repo = context.repo.repo; const number = context.issue.number; @@ -37,20 +42,32 @@ module.exports = async ({github, context}) => { issue_number: number, }); - const isBugTemplate = issue.data.body.includes('Link to the code that reproduces this issue'); + const yamlData = fs.readFileSync(TEMPLATE_FILE_PATH, 'utf8'); + const obj = yaml.load(yamlData); + const linkMatchingText = (obj.body.find(x => {return x.type === 'input' && x.validations.required === true && x.attributes.label.includes('link')})).attributes.label; + const isBugTemplate = issue.data.body.includes(linkMatchingText); if (isBugTemplate) { console.log(`Issue ${number} is a bug template`) try { - const link = issue.data.body.split('\n')[18].match(/(https?:\/\/(gist\.)?github.com\/.*)/)[0]; - console.log(`Issue ${number} contains this link: ${link}`) - const isValidLink = (await fetch(link)).ok; - console.log(`Issue ${number} has a ${isValidLink ? 'valid' : 'invalid'} link`) - if (!isValidLink) { - await closeIssue(github, owner, repo, number); - } + const text = issue.data.body; + const match = text.indexOf(linkMatchingText); + if (match !== -1) { + const nextLineIndex = text.indexOf('http', match); + if (nextLineIndex == -1) { + await closeIssue(github, owner, repo, number); + return; + } + const link = text.substring(nextLineIndex, text.indexOf('\n', nextLineIndex)); + console.log(`Issue ${number} contains this link: ${link}`); + const isValidLink = (await fetch(link)).ok; + console.log(`Issue ${number} has a ${isValidLink ? "valid" : "invalid"} link`) + if (!isValidLink) { + await closeIssue(github, owner, repo, number); + } + } } catch (err) { await closeIssue(github, owner, repo, number); } } -}; +}; \ No newline at end of file diff --git a/.github/scripts/close-unresponsive.cjs b/.github/scripts/close-unresponsive.cjs index 142dc1265..6f81b508f 100644 --- a/.github/scripts/close-unresponsive.cjs +++ b/.github/scripts/close-unresponsive.cjs @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +/// Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -13,57 +13,57 @@ // limitations under the License. function labeledEvent(data) { - return data.event === 'labeled' && data.label.name === 'needs more info'; - } - - const numberOfDaysLimit = 15; - const close_message = `This has been closed since a request for information has \ - not been answered for ${numberOfDaysLimit} days. It can be reopened when the \ - requested information is provided.`; - - module.exports = async ({github, context}) => { - const owner = context.repo.owner; - const repo = context.repo.repo; - - const issues = await github.rest.issues.listForRepo({ - owner: owner, - repo: repo, - labels: 'needs more info', - }); - const numbers = issues.data.map((e) => e.number); - - for (const number of numbers) { - const events = await github.paginate( - github.rest.issues.listEventsForTimeline, - { - owner: owner, - repo: repo, - issue_number: number, - }, - (response) => response.data.filter(labeledEvent) - ); - - const latest_response_label = events[events.length - 1]; - - const created_at = new Date(latest_response_label.created_at); - const now = new Date(); - const diff = now - created_at; - const diffDays = diff / (1000 * 60 * 60 * 24); - - if (diffDays > numberOfDaysLimit) { - await github.rest.issues.update({ - owner: owner, - repo: repo, - issue_number: number, - state: 'closed', - }); - - await github.rest.issues.createComment({ - owner: owner, - repo: repo, - issue_number: number, - body: close_message, - }); - } + return data.event === "labeled" && data.label.name === "needs more info"; +} + +const numberOfDaysLimit = 15; +const close_message = `This has been closed since a request for information has \ +not been answered for ${numberOfDaysLimit} days. It can be reopened when the \ +requested information is provided.`; + +module.exports = async ({ github, context }) => { + const owner = context.repo.owner; + const repo = context.repo.repo; + + const issues = await github.rest.issues.listForRepo({ + owner: owner, + repo: repo, + labels: "needs more info", + }); + const numbers = issues.data.map((e) => e.number); + + for (const number of numbers) { + const events = await github.paginate( + github.rest.issues.listEventsForTimeline, + { + owner: owner, + repo: repo, + issue_number: number, + }, + (response) => response.data.filter(labeledEvent) + ); + + const latest_response_label = events[events.length - 1]; + + const created_at = new Date(latest_response_label.created_at); + const now = new Date(); + const diff = now - created_at; + const diffDays = diff / (1000 * 60 * 60 * 24); + + if (diffDays > numberOfDaysLimit) { + await github.rest.issues.update({ + owner: owner, + repo: repo, + issue_number: number, + state: "closed", + }); + + await github.rest.issues.createComment({ + owner: owner, + repo: repo, + issue_number: number, + body: close_message, + }); } - }; + } +}; \ No newline at end of file diff --git a/.github/scripts/fixtures/invalidIssueBody.txt b/.github/scripts/fixtures/invalidIssueBody.txt new file mode 100644 index 000000000..504bd6690 --- /dev/null +++ b/.github/scripts/fixtures/invalidIssueBody.txt @@ -0,0 +1,50 @@ +### Please make sure you have searched for information in the following guides. + +- [X] Search the issues already opened: https://github.com/GoogleCloudPlatform/google-cloud-node/issues +- [X] Search StackOverflow: http://stackoverflow.com/questions/tagged/google-cloud-platform+node.js +- [X] Check our Troubleshooting guide: https://googlecloudplatform.github.io/google-cloud-node/#/docs/guides/troubleshooting +- [X] Check our FAQ: https://googlecloudplatform.github.io/google-cloud-node/#/docs/guides/faq +- [X] Check our libraries HOW-TO: https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md +- [X] Check out our authentication guide: https://github.com/googleapis/google-auth-library-nodejs +- [X] Check out handwritten samples for many of our APIs: https://github.com/GoogleCloudPlatform/nodejs-docs-samples + +### A screenshot that you have tested with "Try this API". + + +N/A + +### Link to the code that reproduces this issue. A link to a **public** Github Repository or gist with a minimal reproduction. + +not-a-link + +### A step-by-step description of how to reproduce the issue, based on the linked reproduction. + + +Change MY_PROJECT to your project name, add credentials if needed and run. + +### A clear and concise description of what the bug is, and what you expected to happen. + +The application crashes with the following exception (which there is no way to catch). It should just emit error, and allow graceful handling. +TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object + at _write (node:internal/streams/writable:474:13) + at Writable.write (node:internal/streams/writable:502:10) + at Duplexify._write (/project/node_modules/duplexify/index.js:212:22) + at doWrite (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:390:139) + at writeOrBuffer (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:381:5) + at Writable.write (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:302:11) + at Pumpify. (/project/node_modules/@google-cloud/speech/build/src/helpers.js:79:27) + at Object.onceWrapper (node:events:633:26) + at Pumpify.emit (node:events:518:28) + at obj. [as _write] (/project/node_modules/stubs/index.js:28:22) + at doWrite (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:390:139) + at writeOrBuffer (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:381:5) + at Writable.write (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:302:11) + at PassThrough.ondata (node:internal/streams/readable:1007:22) + at PassThrough.emit (node:events:518:28) + at addChunk (node:internal/streams/readable:559:12) { + code: 'ERR_INVALID_ARG_TYPE' + + +### A clear and concise description WHY you expect this behavior, i.e., was it a recent change, there is documentation that points to this behavior, etc. ** + +No library should crash an application this way. \ No newline at end of file diff --git a/.github/scripts/fixtures/validIssueBody.txt b/.github/scripts/fixtures/validIssueBody.txt new file mode 100644 index 000000000..6e0ace338 --- /dev/null +++ b/.github/scripts/fixtures/validIssueBody.txt @@ -0,0 +1,50 @@ +### Please make sure you have searched for information in the following guides. + +- [X] Search the issues already opened: https://github.com/GoogleCloudPlatform/google-cloud-node/issues +- [X] Search StackOverflow: http://stackoverflow.com/questions/tagged/google-cloud-platform+node.js +- [X] Check our Troubleshooting guide: https://googlecloudplatform.github.io/google-cloud-node/#/docs/guides/troubleshooting +- [X] Check our FAQ: https://googlecloudplatform.github.io/google-cloud-node/#/docs/guides/faq +- [X] Check our libraries HOW-TO: https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md +- [X] Check out our authentication guide: https://github.com/googleapis/google-auth-library-nodejs +- [X] Check out handwritten samples for many of our APIs: https://github.com/GoogleCloudPlatform/nodejs-docs-samples + +### A screenshot that you have tested with "Try this API". + + +N/A + +### Link to the code that reproduces this issue. A link to a **public** Github Repository or gist with a minimal reproduction. + +https://gist.github.com/orgads/13cbf44c91923da27d8772b5f10489c9 + +### A step-by-step description of how to reproduce the issue, based on the linked reproduction. + + +Change MY_PROJECT to your project name, add credentials if needed and run. + +### A clear and concise description of what the bug is, and what you expected to happen. + +The application crashes with the following exception (which there is no way to catch). It should just emit error, and allow graceful handling. +TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object + at _write (node:internal/streams/writable:474:13) + at Writable.write (node:internal/streams/writable:502:10) + at Duplexify._write (/project/node_modules/duplexify/index.js:212:22) + at doWrite (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:390:139) + at writeOrBuffer (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:381:5) + at Writable.write (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:302:11) + at Pumpify. (/project/node_modules/@google-cloud/speech/build/src/helpers.js:79:27) + at Object.onceWrapper (node:events:633:26) + at Pumpify.emit (node:events:518:28) + at obj. [as _write] (/project/node_modules/stubs/index.js:28:22) + at doWrite (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:390:139) + at writeOrBuffer (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:381:5) + at Writable.write (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:302:11) + at PassThrough.ondata (node:internal/streams/readable:1007:22) + at PassThrough.emit (node:events:518:28) + at addChunk (node:internal/streams/readable:559:12) { + code: 'ERR_INVALID_ARG_TYPE' + + +### A clear and concise description WHY you expect this behavior, i.e., was it a recent change, there is documentation that points to this behavior, etc. ** + +No library should crash an application this way. \ No newline at end of file diff --git a/.github/scripts/fixtures/validIssueBodyDifferentLinkLocation.txt b/.github/scripts/fixtures/validIssueBodyDifferentLinkLocation.txt new file mode 100644 index 000000000..984a420e3 --- /dev/null +++ b/.github/scripts/fixtures/validIssueBodyDifferentLinkLocation.txt @@ -0,0 +1,50 @@ +### Please make sure you have searched for information in the following guides. + +- [X] Search the issues already opened: https://github.com/GoogleCloudPlatform/google-cloud-node/issues +- [X] Search StackOverflow: http://stackoverflow.com/questions/tagged/google-cloud-platform+node.js +- [X] Check our Troubleshooting guide: https://googlecloudplatform.github.io/google-cloud-node/#/docs/guides/troubleshooting +- [X] Check our FAQ: https://googlecloudplatform.github.io/google-cloud-node/#/docs/guides/faq +- [X] Check our libraries HOW-TO: https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md +- [X] Check out our authentication guide: https://github.com/googleapis/google-auth-library-nodejs +- [X] Check out handwritten samples for many of our APIs: https://github.com/GoogleCloudPlatform/nodejs-docs-samples + +### A screenshot that you have tested with "Try this API". + + +N/A + +### A step-by-step description of how to reproduce the issue, based on the linked reproduction. + + +Change MY_PROJECT to your project name, add credentials if needed and run. + +### A clear and concise description of what the bug is, and what you expected to happen. + +The application crashes with the following exception (which there is no way to catch). It should just emit error, and allow graceful handling. +TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object + at _write (node:internal/streams/writable:474:13) + at Writable.write (node:internal/streams/writable:502:10) + at Duplexify._write (/project/node_modules/duplexify/index.js:212:22) + at doWrite (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:390:139) + at writeOrBuffer (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:381:5) + at Writable.write (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:302:11) + at Pumpify. (/project/node_modules/@google-cloud/speech/build/src/helpers.js:79:27) + at Object.onceWrapper (node:events:633:26) + at Pumpify.emit (node:events:518:28) + at obj. [as _write] (/project/node_modules/stubs/index.js:28:22) + at doWrite (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:390:139) + at writeOrBuffer (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:381:5) + at Writable.write (/project/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js:302:11) + at PassThrough.ondata (node:internal/streams/readable:1007:22) + at PassThrough.emit (node:events:518:28) + at addChunk (node:internal/streams/readable:559:12) { + code: 'ERR_INVALID_ARG_TYPE' + +### Link to the code that reproduces this issue. A link to a **public** Github Repository with a minimal reproduction. + + +https://gist.github.com/orgads/13cbf44c91923da27d8772b5f10489c9 + +### A clear and concise description WHY you expect this behavior, i.e., was it a recent change, there is documentation that points to this behavior, etc. ** + +No library should crash an application this way. \ No newline at end of file diff --git a/.github/scripts/package.json b/.github/scripts/package.json new file mode 100644 index 000000000..2c2e5207d --- /dev/null +++ b/.github/scripts/package.json @@ -0,0 +1,21 @@ +{ + "name": "tests", + "private": true, + "description": "tests for script", + "scripts": { + "test": "mocha tests/close-invalid-link.test.cjs && mocha tests/close-or-remove-response-label.test.cjs" + }, + "author": "Google Inc.", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "dependencies": { + "js-yaml": "^4.1.0" + }, + "devDependencies": { + "@octokit/rest": "^19.0.0", + "mocha": "^10.0.0", + "sinon": "^18.0.0" + } +} \ No newline at end of file diff --git a/.github/scripts/remove-response-label.cjs b/.github/scripts/remove-response-label.cjs index 887cf349e..4a784ddf7 100644 --- a/.github/scripts/remove-response-label.cjs +++ b/.github/scripts/remove-response-label.cjs @@ -13,21 +13,21 @@ // limitations under the License. module.exports = async ({ github, context }) => { - const commenter = context.actor; - const issue = await github.rest.issues.get({ + const commenter = context.actor; + const issue = await github.rest.issues.get({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + }); + const author = issue.data.user.login; + const labels = issue.data.labels.map((e) => e.name); + + if (author === commenter && labels.includes("needs more info")) { + await github.rest.issues.removeLabel({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, + name: "needs more info", }); - const author = issue.data.user.login; - const labels = issue.data.labels.map((e) => e.name); - - if (author === commenter && labels.includes('needs more info')) { - await github.rest.issues.removeLabel({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - name: 'needs more info', - }); - } - }; + } +}; \ No newline at end of file diff --git a/.github/scripts/tests/close-invalid-link.test.cjs b/.github/scripts/tests/close-invalid-link.test.cjs new file mode 100644 index 000000000..f63ee89c8 --- /dev/null +++ b/.github/scripts/tests/close-invalid-link.test.cjs @@ -0,0 +1,86 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +const { describe, it } = require('mocha'); +const closeInvalidLink = require('../close-invalid-link.cjs'); +const fs = require('fs'); +const sinon = require('sinon'); + +describe('close issues with invalid links', () => { + let octokitStub; + let issuesStub; + + beforeEach(() => { + issuesStub = { + get: sinon.stub(), + createComment: sinon.stub(), + update: sinon.stub(), + }; + octokitStub = { + rest: { + issues: issuesStub, + }, + }; + }); + + afterEach(() => { + sinon.restore(); + }); + + it('does not do anything if it is not a bug', async () => { + const context = { repo: { owner: 'testOrg', repo: 'testRepo' }, issue: { number: 1 } }; + issuesStub.get.resolves({ data: { body: "I'm having a problem with this." } }); + + await closeInvalidLink({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.get); + sinon.assert.notCalled(issuesStub.createComment); + sinon.assert.notCalled(issuesStub.update); + }); + + it('does not do anything if it is a bug with an appropriate link', async () => { + const context = { repo: { owner: 'testOrg', repo: 'testRepo' }, issue: { number: 1 } }; + issuesStub.get.resolves({ data: { body: fs.readFileSync('./fixtures/validIssueBody.txt', 'utf-8') } }); + + await closeInvalidLink({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.get); + sinon.assert.notCalled(issuesStub.createComment); + sinon.assert.notCalled(issuesStub.update); + }); + + it('does not do anything if it is a bug with an appropriate link and the template changes', async () => { + const context = { repo: { owner: 'testOrg', repo: 'testRepo' }, issue: { number: 1 } }; + issuesStub.get.resolves({ data: { body: fs.readFileSync('./fixtures/validIssueBodyDifferentLinkLocation.txt', 'utf-8') } }); + + await closeInvalidLink({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.get); + sinon.assert.notCalled(issuesStub.createComment); + sinon.assert.notCalled(issuesStub.update); + }); + + it('closes the issue if the link is invalid', async () => { + const context = { repo: { owner: 'testOrg', repo: 'testRepo' }, issue: { number: 1 } }; + issuesStub.get.resolves({ data: { body: fs.readFileSync('./fixtures/invalidIssueBody.txt', 'utf-8') } }); + + await closeInvalidLink({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.get); + sinon.assert.calledOnce(issuesStub.createComment); + sinon.assert.calledOnce(issuesStub.update); + }); +}); \ No newline at end of file diff --git a/.github/scripts/tests/close-or-remove-response-label.test.cjs b/.github/scripts/tests/close-or-remove-response-label.test.cjs new file mode 100644 index 000000000..fb092c536 --- /dev/null +++ b/.github/scripts/tests/close-or-remove-response-label.test.cjs @@ -0,0 +1,109 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +const { describe, it, beforeEach, afterEach } = require('mocha'); +const removeResponseLabel = require('../remove-response-label.cjs'); +const closeUnresponsive = require('../close-unresponsive.cjs'); +const sinon = require('sinon'); + +function getISODateDaysAgo(days) { + const today = new Date(); + const daysAgo = new Date(today.setDate(today.getDate() - days)); + return daysAgo.toISOString(); +} + +describe('close issues or remove needs more info labels', () => { + let octokitStub; + let issuesStub; + let paginateStub; + + beforeEach(() => { + issuesStub = { + listForRepo: sinon.stub(), + update: sinon.stub(), + createComment: sinon.stub(), + get: sinon.stub(), + removeLabel: sinon.stub(), + }; + paginateStub = sinon.stub(); + octokitStub = { + rest: { + issues: issuesStub, + }, + paginate: paginateStub, + }; + }); + + afterEach(() => { + sinon.restore(); + }); + + it('closes the issue if the OP has not responded within the allotted time and there is a needs-more-info label', async () => { + const context = { owner: 'testOrg', repo: 'testRepo' }; + const issuesInRepo = [{ user: { login: 'OP' }, labels: [{ name: 'needs more info' }] }]; + const eventsInIssue = [{ event: 'labeled', label: { name: 'needs more info' }, created_at: getISODateDaysAgo(16) }]; + + issuesStub.listForRepo.resolves({ data: issuesInRepo }); + paginateStub.resolves(eventsInIssue); + + await closeUnresponsive({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.listForRepo); + sinon.assert.calledOnce(paginateStub); + sinon.assert.calledOnce(issuesStub.update); + sinon.assert.calledOnce(issuesStub.createComment); + }); + + it('does nothing if not enough time has passed and there is a needs-more-info label', async () => { + const context = { owner: 'testOrg', repo: 'testRepo' }; + const issuesInRepo = [{ user: { login: 'OP' }, labels: [{ name: 'needs more info' }] }]; + const eventsInIssue = [{ event: 'labeled', label: { name: 'needs more info' }, created_at: getISODateDaysAgo(14) }]; + + issuesStub.listForRepo.resolves({ data: issuesInRepo }); + paginateStub.resolves(eventsInIssue); + + await closeUnresponsive({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.listForRepo); + sinon.assert.calledOnce(paginateStub); + sinon.assert.notCalled(issuesStub.update); + sinon.assert.notCalled(issuesStub.createComment); + }); + + it('removes the label if OP responded', async () => { + const context = { actor: 'OP', repo: { owner: 'testOrg', repo: 'testRepo' }, issue: { number: 1 } }; + const issueContext = { user: {login: 'OP'}, labels: [{ name: 'needs more info' }] }; + + issuesStub.get.resolves({ data: issueContext }); + + await removeResponseLabel({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.get); + sinon.assert.calledOnce(issuesStub.removeLabel); + }); + + it('does not remove the label if author responded', async () => { + const context = { actor: 'repo-maintainer', repo: { owner: 'testOrg', repo: 'testRepo' }, issue: { number: 1 } }; + const issueContext = { user: {login: 'OP'}, labels: [{ name: 'needs more info' }] }; + + issuesStub.get.resolves({ data: issueContext }); + + await removeResponseLabel({ github: octokitStub, context }); + + sinon.assert.calledOnce(issuesStub.get); + sinon.assert.notCalled(issuesStub.removeLabel); + }); +}); \ No newline at end of file diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index b46e4c4d6..a013376d1 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -8,9 +8,9 @@ branchProtectionRules: - "ci/kokoro: Samples test" - "ci/kokoro: System test" - lint - - test (14) - - test (16) - test (18) + - test (20) + - test (22) - cla/google - windows - OwlBot Post Processor diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4892eb2c5..883082c0b 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,10 +9,10 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16, 18, 20] + node: [18, 20, 22] steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node }} - run: node --version @@ -26,13 +26,27 @@ jobs: - run: npm test env: MOCHA_THROW_DEPRECATION: false + test-script: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 18 + - run: node --version + - run: npm install --engine-strict + working-directory: .github/scripts + - run: npm test + working-directory: .github/scripts + env: + MOCHA_THROW_DEPRECATION: false windows: runs-on: windows-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: npm install --engine-strict - run: npm test env: @@ -40,19 +54,19 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: npm install - run: npm run lint docs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: npm install - run: npm run docs - uses: JustinBeckwith/linkinator-action@v1 diff --git a/.github/workflows/issues-no-repro.yaml b/.github/workflows/issues-no-repro.yaml index 442a46bcc..9b2f70148 100644 --- a/.github/workflows/issues-no-repro.yaml +++ b/.github/workflows/issues-no-repro.yaml @@ -11,6 +11,11 @@ jobs: pull-requests: write steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v3 + with: + node-version: 18 + - run: npm install + working-directory: ./.github/scripts - uses: actions/github-script@v7 with: script: | diff --git a/.kokoro/common.cfg b/.kokoro/common.cfg index d8038cd99..dabc141b2 100644 --- a/.kokoro/common.cfg +++ b/.kokoro/common.cfg @@ -16,7 +16,7 @@ build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" diff --git a/.kokoro/continuous/node14/common.cfg b/.kokoro/continuous/node18/common.cfg similarity index 89% rename from .kokoro/continuous/node14/common.cfg rename to .kokoro/continuous/node18/common.cfg index d8038cd99..dabc141b2 100644 --- a/.kokoro/continuous/node14/common.cfg +++ b/.kokoro/continuous/node18/common.cfg @@ -16,7 +16,7 @@ build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" diff --git a/.kokoro/continuous/node14/lint.cfg b/.kokoro/continuous/node18/lint.cfg similarity index 100% rename from .kokoro/continuous/node14/lint.cfg rename to .kokoro/continuous/node18/lint.cfg diff --git a/.kokoro/continuous/node14/samples-test.cfg b/.kokoro/continuous/node18/samples-test.cfg similarity index 100% rename from .kokoro/continuous/node14/samples-test.cfg rename to .kokoro/continuous/node18/samples-test.cfg diff --git a/.kokoro/continuous/node14/system-test.cfg b/.kokoro/continuous/node18/system-test.cfg similarity index 100% rename from .kokoro/continuous/node14/system-test.cfg rename to .kokoro/continuous/node18/system-test.cfg diff --git a/.kokoro/continuous/node14/test.cfg b/.kokoro/continuous/node18/test.cfg similarity index 100% rename from .kokoro/continuous/node14/test.cfg rename to .kokoro/continuous/node18/test.cfg diff --git a/.kokoro/presubmit/node14/common.cfg b/.kokoro/presubmit/node18/common.cfg similarity index 89% rename from .kokoro/presubmit/node14/common.cfg rename to .kokoro/presubmit/node18/common.cfg index d8038cd99..dabc141b2 100644 --- a/.kokoro/presubmit/node14/common.cfg +++ b/.kokoro/presubmit/node18/common.cfg @@ -16,7 +16,7 @@ build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" diff --git a/.kokoro/presubmit/node14/samples-test.cfg b/.kokoro/presubmit/node18/samples-test.cfg similarity index 100% rename from .kokoro/presubmit/node14/samples-test.cfg rename to .kokoro/presubmit/node18/samples-test.cfg diff --git a/.kokoro/presubmit/node14/system-test.cfg b/.kokoro/presubmit/node18/system-test.cfg similarity index 100% rename from .kokoro/presubmit/node14/system-test.cfg rename to .kokoro/presubmit/node18/system-test.cfg diff --git a/.kokoro/presubmit/node14/test.cfg b/.kokoro/presubmit/node18/test.cfg similarity index 100% rename from .kokoro/presubmit/node14/test.cfg rename to .kokoro/presubmit/node18/test.cfg diff --git a/.kokoro/release/docs-devsite.cfg b/.kokoro/release/docs-devsite.cfg index b5638214a..b1ebf97bc 100644 --- a/.kokoro/release/docs-devsite.cfg +++ b/.kokoro/release/docs-devsite.cfg @@ -11,7 +11,7 @@ before_action { # doc publications use a Python image. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } # Download trampoline resources. diff --git a/.kokoro/release/docs.cfg b/.kokoro/release/docs.cfg index 508a0efda..ef7147c33 100644 --- a/.kokoro/release/docs.cfg +++ b/.kokoro/release/docs.cfg @@ -11,7 +11,7 @@ before_action { # doc publications use a Python image. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } # Download trampoline resources. diff --git a/.kokoro/release/docs.sh b/.kokoro/release/docs.sh index 1d8f3f490..e9079a605 100755 --- a/.kokoro/release/docs.sh +++ b/.kokoro/release/docs.sh @@ -16,7 +16,7 @@ set -eo pipefail -# build jsdocs (Python is installed on the Node 10 docker image). +# build jsdocs (Python is installed on the Node 18 docker image). if [[ -z "$CREDENTIALS" ]]; then # if CREDENTIALS are explicitly set, assume we're testing locally # and don't set NPM_CONFIG_PREFIX. diff --git a/.kokoro/release/publish.cfg b/.kokoro/release/publish.cfg index 91fb161ec..ae6223c88 100644 --- a/.kokoro/release/publish.cfg +++ b/.kokoro/release/publish.cfg @@ -30,7 +30,7 @@ build_file: "nodejs-pubsub/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { diff --git a/.kokoro/samples-test.sh b/.kokoro/samples-test.sh index 8c5d108cb..528775394 100755 --- a/.kokoro/samples-test.sh +++ b/.kokoro/samples-test.sh @@ -16,7 +16,9 @@ set -eo pipefail -export NPM_CONFIG_PREFIX=${HOME}/.npm-global +# Ensure the npm global directory is writable, otherwise rebuild `npm` +mkdir -p $NPM_CONFIG_PREFIX +npm config -g ls || npm i -g npm@`npm --version` # Setup service account credentials. export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/long-door-651-kokoro-system-test-service-account @@ -56,7 +58,7 @@ fi # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/system-test.sh b/.kokoro/system-test.sh index 0b3043d26..a90d5cfec 100755 --- a/.kokoro/system-test.sh +++ b/.kokoro/system-test.sh @@ -49,7 +49,7 @@ npm run system-test # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/test.bat b/.kokoro/test.bat index 0bb124052..caf825656 100644 --- a/.kokoro/test.bat +++ b/.kokoro/test.bat @@ -21,7 +21,7 @@ cd .. @rem we upgrade Node.js in the image: SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm -call nvm use v14.17.3 +call nvm use 18 call which node call npm install || goto :error diff --git a/.kokoro/test.sh b/.kokoro/test.sh index 862d478d3..0d9f6392a 100755 --- a/.kokoro/test.sh +++ b/.kokoro/test.sh @@ -39,7 +39,7 @@ npm test # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/trampoline_v2.sh b/.kokoro/trampoline_v2.sh index 4d0311212..5d6cfcca5 100755 --- a/.kokoro/trampoline_v2.sh +++ b/.kokoro/trampoline_v2.sh @@ -44,7 +44,7 @@ # the project root. # # Here is an example for running this script. -# TRAMPOLINE_IMAGE=gcr.io/cloud-devrel-kokoro-resources/node:10-user \ +# TRAMPOLINE_IMAGE=gcr.io/cloud-devrel-kokoro-resources/node:18-user \ # TRAMPOLINE_BUILD_FILE=.kokoro/system-test.sh \ # .kokoro/trampoline_v2.sh diff --git a/README.md b/README.md index 1db6a6e2e..4972a7433 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ const {PubSub} = require('@google-cloud/pubsub'); async function quickstart( projectId = 'your-project-id', // Your Google Cloud Platform project ID topicNameOrId = 'my-topic', // Name for the new topic to create - subscriptionName = 'my-sub' // Name for the new subscription to create + subscriptionName = 'my-sub', // Name for the new subscription to create ) { // Instantiates a client const pubsub = new PubSub({projectId}); @@ -96,7 +96,7 @@ async function quickstart( }); // Send a message to the topic - topic.publishMessage({data: Buffer.from('Test message!')}); + await topic.publishMessage({data: Buffer.from('Test message!')}); } ``` diff --git a/bin/benchwrapper.js b/bin/benchwrapper.js index 3b8a6d91f..f272b4ccf 100644 --- a/bin/benchwrapper.js +++ b/bin/benchwrapper.js @@ -76,5 +76,5 @@ server.bindAsync( } else { server.start(); } - } + }, ); diff --git a/owlbot.py b/owlbot.py index fb4ebecc1..fd1d28c98 100644 --- a/owlbot.py +++ b/owlbot.py @@ -13,21 +13,6 @@ # limitations under the License. from synthtool.languages import node -from synthtool import shell -from synthtool.log import logger - -# Generate JS samples from TS. -# node.typeless_samples_hermetic() - -# We need to run this before the main owlbot processing, to make -# sure quickstart.js gets gts fixed before the README is generated. -# This needs to be worked out more properly, this is temporary. -logger.debug("Run typeless sample bot") -node.install() -shell.run(["npm", "run", "typeless"]) - -# node.fix() - # Main OwlBot processing. node.owlbot_main(templates_excludes=[ diff --git a/package.json b/package.json index 599e15c3a..2bbee45d0 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "author": "Google Inc.", "engines": { - "node": ">=14.0.0" + "node": ">=18" }, "repository": "googleapis/nodejs-pubsub", "main": "./build/src/index.js", @@ -45,66 +45,64 @@ "predocs-test": "npm run docs", "benchwrapper": "node bin/benchwrapper.js", "prelint": "cd samples; npm link ../; npm install", - "precompile": "gts clean", - "typeless": "npx typeless-sample-bot --outputpath samples --targets samples --recursive", - "posttypeless": "npm run link-samples && npx eslint --ignore-pattern owl-bot-staging --fix samples" + "precompile": "gts clean" }, "dependencies": { - "@google-cloud/paginator": "^5.0.0", - "@google-cloud/precise-date": "^4.0.0", - "@google-cloud/projectify": "^4.0.0", - "@google-cloud/promisify": "~4.0.0", + "@google-cloud/paginator": "^6.0.0", + "@google-cloud/precise-date": "^5.0.0", + "@google-cloud/projectify": "^5.0.0", + "@google-cloud/promisify": "^5.0.0", "@opentelemetry/api": "~1.9.0", - "@opentelemetry/semantic-conventions": "~1.30.0", + "@opentelemetry/semantic-conventions": "~1.32.0", "arrify": "^2.0.0", "extend": "^3.0.2", - "google-auth-library": "^9.3.0", - "google-gax": "^4.3.3", - "heap-js": "^2.2.0", + "google-auth-library": "^10.0.0-rc.1", + "google-gax": "^5.0.1-rc.0", + "heap-js": "^2.6.0", "is-stream-ended": "^0.1.4", "lodash.snakecase": "^4.1.1", "p-defer": "^3.0.0" }, "devDependencies": { - "@google-cloud/typeless-sample-bot": "^2.1.0", - "@grpc/proto-loader": "^0.7.0", + "@grpc/proto-loader": "^0.7.13", "@opentelemetry/core": "^1.17.0", "@opentelemetry/sdk-trace-base": "^1.17.0", "@types/duplexify": "^3.6.4", - "@types/extend": "^3.0.0", - "@types/lodash.snakecase": "^4.1.6", - "@types/mocha": "^9.0.0", - "@types/mv": "^2.1.0", - "@types/ncp": "^2.0.1", - "@types/node": "^22.0.0", - "@types/proxyquire": "^1.3.28", - "@types/sinon": "^17.0.0", - "@types/tmp": "^0.2.0", + "@types/extend": "^3.0.4", + "@types/lodash.snakecase": "^4.1.9", + "@types/mocha": "^10.0.10", + "@types/mv": "^2.1.4", + "@types/ncp": "^2.0.8", + "@types/node": "^22.14.1", + "@types/proxyquire": "^1.3.31", + "@types/sinon": "^17.0.4", + "@types/tmp": "^0.2.6", "@types/uuid": "^10.0.0", - "c8": "^9.0.0", - "codecov": "^3.0.0", - "execa": "^5.0.0", - "gapic-tools": "^0.4.0", - "gts": "^5.0.0", - "jsdoc": "^4.0.0", + "c8": "^10.1.3", + "codecov": "^3.8.3", + "execa": "~5.0.0", + "gapic-tools": "^1.0.1", + "gts": "^6.0.2", + "jsdoc": "^4.0.4", "jsdoc-fresh": "^3.0.0", "jsdoc-region-tag": "^3.0.0", - "linkinator": "~4.0.0", - "mocha": "^9.2.2", + "linkinator": "^6.1.2", + "mocha": "^11.1.0", "mv": "^2.1.1", "ncp": "^2.0.0", - "nise": "6.0.0", - "null-loader": "^4.0.0", - "path-to-regexp": "6.2.2", - "protobufjs": "^7.0.0", - "proxyquire": "^2.0.0", - "sinon": "^18.0.0", - "tmp": "^0.2.0", - "ts-loader": "^9.0.0", - "typescript": "^5.1.6", - "uuid": "^9.0.0", - "webpack": "^5.0.0", - "webpack-cli": "^5.0.0", - "yargs": "^16.0.0" + "nise": "^6.1.1", + "null-loader": "^4.0.1", + "path-to-regexp": "^8.2.0", + "protobufjs": "^7.4.0", + "proxyquire": "^2.1.3", + "sinon": "^20.0.0", + "tmp": "^0.2.3", + "ts-loader": "^9.5.2", + "typescript": "^5.8.3", + "uuid": "^11.1.0", + "webpack": "^5.99.5", + "webpack-cli": "^6.0.1", + "why-is-node-running": "^2.3.0", + "yargs": "^17.7.2" } } diff --git a/protos/protos.d.ts b/protos/protos.d.ts index 3ccad3fc0..b61594d6b 100644 --- a/protos/protos.d.ts +++ b/protos/protos.d.ts @@ -2658,7 +2658,7 @@ export namespace google { interface IPubsubMessage { /** PubsubMessage data */ - data?: (Uint8Array|string|null); + data?: (Uint8Array|Buffer|string|null); /** PubsubMessage attributes */ attributes?: ({ [k: string]: string }|null); @@ -2683,7 +2683,7 @@ export namespace google { constructor(properties?: google.pubsub.v1.IPubsubMessage); /** PubsubMessage data. */ - public data: (Uint8Array|string); + public data: (Uint8Array|Buffer|string); /** PubsubMessage attributes. */ public attributes: { [k: string]: string }; @@ -10303,7 +10303,7 @@ export namespace google { schema?: (google.pubsub.v1.ISchema|null); /** ValidateMessageRequest message */ - message?: (Uint8Array|string|null); + message?: (Uint8Array|Buffer|string|null); /** ValidateMessageRequest encoding */ encoding?: (google.pubsub.v1.Encoding|keyof typeof google.pubsub.v1.Encoding|null); @@ -10328,7 +10328,7 @@ export namespace google { public schema?: (google.pubsub.v1.ISchema|null); /** ValidateMessageRequest message. */ - public message: (Uint8Array|string); + public message: (Uint8Array|Buffer|string); /** ValidateMessageRequest encoding. */ public encoding: (google.pubsub.v1.Encoding|keyof typeof google.pubsub.v1.Encoding); @@ -15684,7 +15684,7 @@ export namespace google { doubleValue?: (number|null); /** UninterpretedOption stringValue */ - stringValue?: (Uint8Array|string|null); + stringValue?: (Uint8Array|Buffer|string|null); /** UninterpretedOption aggregateValue */ aggregateValue?: (string|null); @@ -15715,7 +15715,7 @@ export namespace google { public doubleValue: number; /** UninterpretedOption stringValue. */ - public stringValue: (Uint8Array|string); + public stringValue: (Uint8Array|Buffer|string); /** UninterpretedOption aggregateValue. */ public aggregateValue: string; diff --git a/protos/protos.js b/protos/protos.js index bc3604fdb..e2eefc5e4 100644 --- a/protos/protos.js +++ b/protos/protos.js @@ -487,12 +487,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - MessageStoragePolicy.decode = function decode(reader, length) { + MessageStoragePolicy.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.MessageStoragePolicy(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.allowedPersistenceRegions && message.allowedPersistenceRegions.length)) @@ -750,12 +752,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SchemaSettings.decode = function decode(reader, length) { + SchemaSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.SchemaSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.schema = reader.string(); @@ -1083,12 +1087,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - IngestionDataSourceSettings.decode = function decode(reader, length) { + IngestionDataSourceSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.awsKinesis = $root.google.pubsub.v1.IngestionDataSourceSettings.AwsKinesis.decode(reader, reader.uint32()); @@ -1451,12 +1457,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AwsKinesis.decode = function decode(reader, length) { + AwsKinesis.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.AwsKinesis(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.state = reader.int32(); @@ -1844,12 +1852,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CloudStorage.decode = function decode(reader, length) { + CloudStorage.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.CloudStorage(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.state = reader.int32(); @@ -2227,12 +2237,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TextFormat.decode = function decode(reader, length) { + TextFormat.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.CloudStorage.TextFormat(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.delimiter = reader.string(); @@ -2423,12 +2435,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AvroFormat.decode = function decode(reader, length) { + AvroFormat.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.CloudStorage.AvroFormat(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -2598,12 +2612,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PubSubAvroFormat.decode = function decode(reader, length) { + PubSubAvroFormat.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.CloudStorage.PubSubAvroFormat(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -2864,12 +2880,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AzureEventHubs.decode = function decode(reader, length) { + AzureEventHubs.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.AzureEventHubs(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.state = reader.int32(); @@ -3271,12 +3289,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AwsMsk.decode = function decode(reader, length) { + AwsMsk.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.AwsMsk(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.state = reader.int32(); @@ -3639,12 +3659,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ConfluentCloud.decode = function decode(reader, length) { + ConfluentCloud.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionDataSourceSettings.ConfluentCloud(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.state = reader.int32(); @@ -3974,12 +3996,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PlatformLogsSettings.decode = function decode(reader, length) { + PlatformLogsSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PlatformLogsSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.severity = reader.int32(); @@ -4307,12 +4331,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - IngestionFailureEvent.decode = function decode(reader, length) { + IngestionFailureEvent.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = reader.string(); @@ -4604,12 +4630,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiViolationReason.decode = function decode(reader, length) { + ApiViolationReason.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent.ApiViolationReason(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -4779,12 +4807,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AvroFailureReason.decode = function decode(reader, length) { + AvroFailureReason.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent.AvroFailureReason(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -5023,12 +5053,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CloudStorageFailure.decode = function decode(reader, length) { + CloudStorageFailure.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent.CloudStorageFailure(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.bucket = reader.string(); @@ -5370,12 +5402,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AwsMskFailureReason.decode = function decode(reader, length) { + AwsMskFailureReason.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent.AwsMskFailureReason(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.clusterArn = reader.string(); @@ -5719,12 +5753,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AzureEventHubsFailureReason.decode = function decode(reader, length) { + AzureEventHubsFailureReason.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent.AzureEventHubsFailureReason(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.namespace = reader.string(); @@ -6068,12 +6104,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ConfluentCloudFailureReason.decode = function decode(reader, length) { + ConfluentCloudFailureReason.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.IngestionFailureEvent.ConfluentCloudFailureReason(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.clusterId = reader.string(); @@ -6452,12 +6490,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Topic.decode = function decode(reader, length) { + Topic.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.Topic(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -6892,12 +6932,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PubsubMessage.decode = function decode(reader, length) { + PubsubMessage.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PubsubMessage(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.data = reader.bytes(); @@ -7192,12 +7234,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetTopicRequest.decode = function decode(reader, length) { + GetTopicRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.GetTopicRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = reader.string(); @@ -7406,12 +7450,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - UpdateTopicRequest.decode = function decode(reader, length) { + UpdateTopicRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.UpdateTopicRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = $root.google.pubsub.v1.Topic.decode(reader, reader.uint32()); @@ -7645,12 +7691,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PublishRequest.decode = function decode(reader, length) { + PublishRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PublishRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = reader.string(); @@ -7882,12 +7930,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PublishResponse.decode = function decode(reader, length) { + PublishResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PublishResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.messageIds && message.messageIds.length)) @@ -8121,12 +8171,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListTopicsRequest.decode = function decode(reader, length) { + ListTopicsRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListTopicsRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.project = reader.string(); @@ -8362,12 +8414,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListTopicsResponse.decode = function decode(reader, length) { + ListTopicsResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListTopicsResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.topics && message.topics.length)) @@ -8619,12 +8673,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListTopicSubscriptionsRequest.decode = function decode(reader, length) { + ListTopicSubscriptionsRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListTopicSubscriptionsRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = reader.string(); @@ -8860,12 +8916,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListTopicSubscriptionsResponse.decode = function decode(reader, length) { + ListTopicSubscriptionsResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListTopicSubscriptionsResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.subscriptions && message.subscriptions.length)) @@ -9112,12 +9170,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListTopicSnapshotsRequest.decode = function decode(reader, length) { + ListTopicSnapshotsRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListTopicSnapshotsRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = reader.string(); @@ -9353,12 +9413,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListTopicSnapshotsResponse.decode = function decode(reader, length) { + ListTopicSnapshotsResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListTopicSnapshotsResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.snapshots && message.snapshots.length)) @@ -9583,12 +9645,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteTopicRequest.decode = function decode(reader, length) { + DeleteTopicRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DeleteTopicRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.topic = reader.string(); @@ -9786,12 +9850,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DetachSubscriptionRequest.decode = function decode(reader, length) { + DetachSubscriptionRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DetachSubscriptionRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -9978,12 +10044,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DetachSubscriptionResponse.decode = function decode(reader, length) { + DetachSubscriptionResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DetachSubscriptionResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -10927,12 +10995,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Subscription.decode = function decode(reader, length) { + Subscription.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.Subscription(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -11474,12 +11544,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AnalyticsHubSubscriptionInfo.decode = function decode(reader, length) { + AnalyticsHubSubscriptionInfo.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.Subscription.AnalyticsHubSubscriptionInfo(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.listing = reader.string(); @@ -11704,12 +11776,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - RetryPolicy.decode = function decode(reader, length) { + RetryPolicy.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.RetryPolicy(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.minimumBackoff = $root.google.protobuf.Duration.decode(reader, reader.uint32()); @@ -11941,12 +12015,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeadLetterPolicy.decode = function decode(reader, length) { + DeadLetterPolicy.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DeadLetterPolicy(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.deadLetterTopic = reader.string(); @@ -12157,12 +12233,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ExpirationPolicy.decode = function decode(reader, length) { + ExpirationPolicy.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ExpirationPolicy(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.ttl = $root.google.protobuf.Duration.decode(reader, reader.uint32()); @@ -12436,12 +12514,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PushConfig.decode = function decode(reader, length) { + PushConfig.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PushConfig(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.pushEndpoint = reader.string(); @@ -12762,12 +12842,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OidcToken.decode = function decode(reader, length) { + OidcToken.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PushConfig.OidcToken(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.serviceAccountEmail = reader.string(); @@ -12967,12 +13049,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PubsubWrapper.decode = function decode(reader, length) { + PubsubWrapper.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PushConfig.PubsubWrapper(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -13153,12 +13237,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - NoWrapper.decode = function decode(reader, length) { + NoWrapper.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PushConfig.NoWrapper(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.writeMetadata = reader.bool(); @@ -13425,12 +13511,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - BigQueryConfig.decode = function decode(reader, length) { + BigQueryConfig.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.BigQueryConfig(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.table = reader.string(); @@ -13886,12 +13974,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CloudStorageConfig.decode = function decode(reader, length) { + CloudStorageConfig.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.CloudStorageConfig(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.bucket = reader.string(); @@ -14291,12 +14381,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TextConfig.decode = function decode(reader, length) { + TextConfig.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.CloudStorageConfig.TextConfig(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -14488,12 +14580,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AvroConfig.decode = function decode(reader, length) { + AvroConfig.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.CloudStorageConfig.AvroConfig(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.writeMetadata = reader.bool(); @@ -14751,12 +14845,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ReceivedMessage.decode = function decode(reader, length) { + ReceivedMessage.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ReceivedMessage(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.ackId = reader.string(); @@ -14984,12 +15080,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetSubscriptionRequest.decode = function decode(reader, length) { + GetSubscriptionRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.GetSubscriptionRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -15198,12 +15296,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - UpdateSubscriptionRequest.decode = function decode(reader, length) { + UpdateSubscriptionRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.UpdateSubscriptionRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = $root.google.pubsub.v1.Subscription.decode(reader, reader.uint32()); @@ -15446,12 +15546,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSubscriptionsRequest.decode = function decode(reader, length) { + ListSubscriptionsRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSubscriptionsRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.project = reader.string(); @@ -15687,12 +15789,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSubscriptionsResponse.decode = function decode(reader, length) { + ListSubscriptionsResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSubscriptionsResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.subscriptions && message.subscriptions.length)) @@ -15922,12 +16026,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteSubscriptionRequest.decode = function decode(reader, length) { + DeleteSubscriptionRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DeleteSubscriptionRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -16136,12 +16242,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ModifyPushConfigRequest.decode = function decode(reader, length) { + ModifyPushConfigRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ModifyPushConfigRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -16379,12 +16487,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PullRequest.decode = function decode(reader, length) { + PullRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PullRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -16609,12 +16719,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PullResponse.decode = function decode(reader, length) { + PullResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.PullResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.receivedMessages && message.receivedMessages.length)) @@ -16855,12 +16967,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ModifyAckDeadlineRequest.decode = function decode(reader, length) { + ModifyAckDeadlineRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ModifyAckDeadlineRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -17111,12 +17225,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AcknowledgeRequest.decode = function decode(reader, length) { + AcknowledgeRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.AcknowledgeRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -17427,12 +17543,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - StreamingPullRequest.decode = function decode(reader, length) { + StreamingPullRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.StreamingPullRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -17827,12 +17945,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - StreamingPullResponse.decode = function decode(reader, length) { + StreamingPullResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.StreamingPullResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.receivedMessages && message.receivedMessages.length)) @@ -18140,12 +18260,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AcknowledgeConfirmation.decode = function decode(reader, length) { + AcknowledgeConfirmation.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.StreamingPullResponse.AcknowledgeConfirmation(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.ackIds && message.ackIds.length)) @@ -18464,12 +18586,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ModifyAckDeadlineConfirmation.decode = function decode(reader, length) { + ModifyAckDeadlineConfirmation.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.StreamingPullResponse.ModifyAckDeadlineConfirmation(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.ackIds && message.ackIds.length)) @@ -18745,12 +18869,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SubscriptionProperties.decode = function decode(reader, length) { + SubscriptionProperties.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.StreamingPullResponse.SubscriptionProperties(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.exactlyOnceDeliveryEnabled = reader.bool(); @@ -18988,12 +19114,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CreateSnapshotRequest.decode = function decode(reader, length) { + CreateSnapshotRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.CreateSnapshotRequest(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -19261,12 +19389,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - UpdateSnapshotRequest.decode = function decode(reader, length) { + UpdateSnapshotRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.UpdateSnapshotRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.snapshot = $root.google.pubsub.v1.Snapshot.decode(reader, reader.uint32()); @@ -19522,12 +19652,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Snapshot.decode = function decode(reader, length) { + Snapshot.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.Snapshot(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -19801,12 +19933,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetSnapshotRequest.decode = function decode(reader, length) { + GetSnapshotRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.GetSnapshotRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.snapshot = reader.string(); @@ -20026,12 +20160,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSnapshotsRequest.decode = function decode(reader, length) { + ListSnapshotsRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSnapshotsRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.project = reader.string(); @@ -20267,12 +20403,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSnapshotsResponse.decode = function decode(reader, length) { + ListSnapshotsResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSnapshotsResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.snapshots && message.snapshots.length)) @@ -20502,12 +20640,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteSnapshotRequest.decode = function decode(reader, length) { + DeleteSnapshotRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DeleteSnapshotRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.snapshot = reader.string(); @@ -20741,12 +20881,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SeekRequest.decode = function decode(reader, length) { + SeekRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.SeekRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.subscription = reader.string(); @@ -20974,12 +21116,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SeekResponse.decode = function decode(reader, length) { + SeekResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.SeekResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -21569,12 +21713,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Schema.decode = function decode(reader, length) { + Schema.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.Schema(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -21904,12 +22050,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CreateSchemaRequest.decode = function decode(reader, length) { + CreateSchemaRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.CreateSchemaRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.parent = reader.string(); @@ -22148,12 +22296,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetSchemaRequest.decode = function decode(reader, length) { + GetSchemaRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.GetSchemaRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -22421,12 +22571,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSchemasRequest.decode = function decode(reader, length) { + ListSchemasRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSchemasRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.parent = reader.string(); @@ -22698,12 +22850,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSchemasResponse.decode = function decode(reader, length) { + ListSchemasResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSchemasResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.schemas && message.schemas.length)) @@ -22966,12 +23120,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSchemaRevisionsRequest.decode = function decode(reader, length) { + ListSchemaRevisionsRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSchemaRevisionsRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -23243,12 +23399,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListSchemaRevisionsResponse.decode = function decode(reader, length) { + ListSchemaRevisionsResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ListSchemaRevisionsResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.schemas && message.schemas.length)) @@ -23489,12 +23647,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CommitSchemaRequest.decode = function decode(reader, length) { + CommitSchemaRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.CommitSchemaRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -23721,12 +23881,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - RollbackSchemaRequest.decode = function decode(reader, length) { + RollbackSchemaRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.RollbackSchemaRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -23948,12 +24110,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteSchemaRevisionRequest.decode = function decode(reader, length) { + DeleteSchemaRevisionRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DeleteSchemaRevisionRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -24164,12 +24328,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteSchemaRequest.decode = function decode(reader, length) { + DeleteSchemaRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.DeleteSchemaRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -24378,12 +24544,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ValidateSchemaRequest.decode = function decode(reader, length) { + ValidateSchemaRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ValidateSchemaRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.parent = reader.string(); @@ -24588,12 +24756,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ValidateSchemaResponse.decode = function decode(reader, length) { + ValidateSchemaResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ValidateSchemaResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -24832,12 +25002,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ValidateMessageRequest.decode = function decode(reader, length) { + ValidateMessageRequest.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ValidateMessageRequest(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.parent = reader.string(); @@ -25123,12 +25295,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ValidateMessageResponse.decode = function decode(reader, length) { + ValidateMessageResponse.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.pubsub.v1.ValidateMessageResponse(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -25353,12 +25527,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Http.decode = function decode(reader, length) { + Http.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.Http(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.rules && message.rules.length)) @@ -25703,12 +25879,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - HttpRule.decode = function decode(reader, length) { + HttpRule.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.HttpRule(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.selector = reader.string(); @@ -26087,12 +26265,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CustomHttpPattern.decode = function decode(reader, length) { + CustomHttpPattern.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.CustomHttpPattern(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.kind = reader.string(); @@ -26319,12 +26499,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CommonLanguageSettings.decode = function decode(reader, length) { + CommonLanguageSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.CommonLanguageSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.referenceDocsUri = reader.string(); @@ -26688,12 +26870,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ClientLibrarySettings.decode = function decode(reader, length) { + ClientLibrarySettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.ClientLibrarySettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.version = reader.string(); @@ -27217,12 +27401,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Publishing.decode = function decode(reader, length) { + Publishing.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.Publishing(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 2: { if (!(message.methodSettings && message.methodSettings.length)) @@ -27668,12 +27854,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - JavaSettings.decode = function decode(reader, length) { + JavaSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.JavaSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.libraryPackage = reader.string(); @@ -27935,12 +28123,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CppSettings.decode = function decode(reader, length) { + CppSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.CppSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -28143,12 +28333,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PhpSettings.decode = function decode(reader, length) { + PhpSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PhpSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -28351,12 +28543,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - PythonSettings.decode = function decode(reader, length) { + PythonSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -28559,12 +28753,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - NodeSettings.decode = function decode(reader, length) { + NodeSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.NodeSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -28832,12 +29028,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DotnetSettings.decode = function decode(reader, length) { + DotnetSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.DotnetSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -29211,12 +29409,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - RubySettings.decode = function decode(reader, length) { + RubySettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.RubySettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -29419,12 +29619,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GoSettings.decode = function decode(reader, length) { + GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); @@ -29651,12 +29853,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - MethodSettings.decode = function decode(reader, length) { + MethodSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.MethodSettings(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.selector = reader.string(); @@ -29929,12 +30133,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - LongRunning.decode = function decode(reader, length) { + LongRunning.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.MethodSettings.LongRunning(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.initialPollDelay = $root.google.protobuf.Duration.decode(reader, reader.uint32()); @@ -30356,12 +30562,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ResourceDescriptor.decode = function decode(reader, length) { + ResourceDescriptor.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.ResourceDescriptor(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.type = reader.string(); @@ -30751,12 +30959,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ResourceReference.decode = function decode(reader, length) { + ResourceReference.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.ResourceReference(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.type = reader.string(); @@ -30981,12 +31191,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FileDescriptorSet.decode = function decode(reader, length) { + FileDescriptorSet.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FileDescriptorSet(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.file && message.file.length)) @@ -31381,12 +31593,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FileDescriptorProto.decode = function decode(reader, length) { + FileDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FileDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -32048,12 +32262,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DescriptorProto.decode = function decode(reader, length) { + DescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -32533,12 +32749,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ExtensionRange.decode = function decode(reader, length) { + ExtensionRange.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.start = reader.int32(); @@ -32777,12 +32995,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ReservedRange.decode = function decode(reader, length) { + ReservedRange.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DescriptorProto.ReservedRange(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.start = reader.int32(); @@ -33033,12 +33253,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ExtensionRangeOptions.decode = function decode(reader, length) { + ExtensionRangeOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ExtensionRangeOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) @@ -33378,12 +33600,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Declaration.decode = function decode(reader, length) { + Declaration.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.number = reader.int32(); @@ -33757,12 +33981,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FieldDescriptorProto.decode = function decode(reader, length) { + FieldDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -34282,12 +34508,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OneofDescriptorProto.decode = function decode(reader, length) { + OneofDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.OneofDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -34553,12 +34781,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - EnumDescriptorProto.decode = function decode(reader, length) { + EnumDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -34872,12 +35102,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - EnumReservedRange.decode = function decode(reader, length) { + EnumReservedRange.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.start = reader.int32(); @@ -35113,12 +35345,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - EnumValueDescriptorProto.decode = function decode(reader, length) { + EnumValueDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumValueDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -35370,12 +35604,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ServiceDescriptorProto.decode = function decode(reader, length) { + ServiceDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ServiceDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -35678,12 +35914,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - MethodDescriptorProto.decode = function decode(reader, length) { + MethodDescriptorProto.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.MethodDescriptorProto(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.name = reader.string(); @@ -36182,12 +36420,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FileOptions.decode = function decode(reader, length) { + FileOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FileOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.javaPackage = reader.string(); @@ -36802,12 +37042,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - MessageOptions.decode = function decode(reader, length) { + MessageOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.MessageOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.messageSetWireFormat = reader.bool(); @@ -37282,12 +37524,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FieldOptions.decode = function decode(reader, length) { + FieldOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.ctype = reader.int32(); @@ -38013,12 +38257,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - EditionDefault.decode = function decode(reader, length) { + EditionDefault.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.EditionDefault(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 3: { message.edition = reader.int32(); @@ -38309,12 +38555,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OneofOptions.decode = function decode(reader, length) { + OneofOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.OneofOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); @@ -38595,12 +38843,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - EnumOptions.decode = function decode(reader, length) { + EnumOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 2: { message.allowAlias = reader.bool(); @@ -38907,12 +39157,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - EnumValueOptions.decode = function decode(reader, length) { + EnumValueOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumValueOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.deprecated = reader.bool(); @@ -39229,12 +39481,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ServiceOptions.decode = function decode(reader, length) { + ServiceOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ServiceOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 34: { message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); @@ -39577,12 +39831,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - MethodOptions.decode = function decode(reader, length) { + MethodOptions.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.MethodOptions(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 33: { message.deprecated = reader.bool(); @@ -39994,12 +40250,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - UninterpretedOption.decode = function decode(reader, length) { + UninterpretedOption.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.UninterpretedOption(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 2: { if (!(message.name && message.name.length)) @@ -40333,12 +40591,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - NamePart.decode = function decode(reader, length) { + NamePart.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.UninterpretedOption.NamePart(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.namePart = reader.string(); @@ -40609,12 +40869,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FeatureSet.decode = function decode(reader, length) { + FeatureSet.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.fieldPresence = reader.int32(); @@ -41144,12 +41406,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FeatureSetDefaults.decode = function decode(reader, length) { + FeatureSetDefaults.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSetDefaults(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.defaults && message.defaults.length)) @@ -41528,12 +41792,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FeatureSetEditionDefault.decode = function decode(reader, length) { + FeatureSetEditionDefault.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 3: { message.edition = reader.int32(); @@ -41818,12 +42084,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SourceCodeInfo.decode = function decode(reader, length) { + SourceCodeInfo.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.SourceCodeInfo(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.location && message.location.length)) @@ -42093,12 +42361,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Location.decode = function decode(reader, length) { + Location.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.SourceCodeInfo.Location(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.path && message.path.length)) @@ -42404,12 +42674,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GeneratedCodeInfo.decode = function decode(reader, length) { + GeneratedCodeInfo.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.GeneratedCodeInfo(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.annotation && message.annotation.length)) @@ -42672,12 +42944,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Annotation.decode = function decode(reader, length) { + Annotation.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.path && message.path.length)) @@ -42998,12 +43272,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Duration.decode = function decode(reader, length) { + Duration.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Duration(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.seconds = reader.int64(); @@ -43217,12 +43493,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Empty.decode = function decode(reader, length) { + Empty.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Empty(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { default: reader.skipType(tag & 7); @@ -43405,12 +43683,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - FieldMask.decode = function decode(reader, length) { + FieldMask.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldMask(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { if (!(message.paths && message.paths.length)) @@ -43633,12 +43913,14 @@ * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - Timestamp.decode = function decode(reader, length) { + Timestamp.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Timestamp(); while (reader.pos < end) { var tag = reader.uint32(); + if (tag === error) + break; switch (tag >>> 3) { case 1: { message.seconds = reader.int64(); diff --git a/protos/protos.json b/protos/protos.json index 2771ea3bb..4befa0df2 100644 --- a/protos/protos.json +++ b/protos/protos.json @@ -1,7 +1,4 @@ { - "options": { - "syntax": "proto3" - }, "nested": { "google": { "nested": { @@ -3648,6 +3645,7 @@ }, "nested": { "FileDescriptorSet": { + "edition": "proto2", "fields": { "file": { "rule": "repeated", @@ -3657,6 +3655,7 @@ } }, "Edition": { + "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, "EDITION_PROTO2": 998, @@ -3672,6 +3671,7 @@ } }, "FileDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3689,18 +3689,12 @@ "publicDependency": { "rule": "repeated", "type": "int32", - "id": 10, - "options": { - "packed": false - } + "id": 10 }, "weakDependency": { "rule": "repeated", "type": "int32", - "id": 11, - "options": { - "packed": false - } + "id": 11 }, "messageType": { "rule": "repeated", @@ -3741,6 +3735,7 @@ } }, "DescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3823,6 +3818,7 @@ } }, "ExtensionRangeOptions": { + "edition": "proto2", "fields": { "uninterpretedOption": { "rule": "repeated", @@ -3896,6 +3892,7 @@ } }, "FieldDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3975,6 +3972,7 @@ } }, "OneofDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3987,6 +3985,7 @@ } }, "EnumDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -4028,6 +4027,7 @@ } }, "EnumValueDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -4044,6 +4044,7 @@ } }, "ServiceDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -4061,6 +4062,7 @@ } }, "MethodDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -4095,6 +4097,7 @@ } }, "FileOptions": { + "edition": "proto2", "fields": { "javaPackage": { "type": "string", @@ -4236,6 +4239,7 @@ } }, "MessageOptions": { + "edition": "proto2", "fields": { "messageSetWireFormat": { "type": "bool", @@ -4309,6 +4313,7 @@ ] }, "FieldOptions": { + "edition": "proto2", "fields": { "ctype": { "type": "CType", @@ -4370,10 +4375,7 @@ "targets": { "rule": "repeated", "type": "OptionTargetType", - "id": 19, - "options": { - "packed": false - } + "id": 19 }, "editionDefaults": { "rule": "repeated", @@ -4457,6 +4459,7 @@ } }, "OneofOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -4476,6 +4479,7 @@ ] }, "EnumOptions": { + "edition": "proto2", "fields": { "allowAlias": { "type": "bool", @@ -4519,6 +4523,7 @@ ] }, "EnumValueOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -4552,6 +4557,7 @@ ] }, "ServiceOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -4578,6 +4584,7 @@ ] }, "MethodOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -4620,6 +4627,7 @@ } }, "UninterpretedOption": { + "edition": "proto2", "fields": { "name": { "rule": "repeated", @@ -4669,6 +4677,7 @@ } }, "FeatureSet": { + "edition": "proto2", "fields": { "fieldPresence": { "type": "FieldPresence", @@ -4810,6 +4819,7 @@ } }, "FeatureSetDefaults": { + "edition": "proto2", "fields": { "defaults": { "rule": "repeated", @@ -4841,6 +4851,7 @@ } }, "SourceCodeInfo": { + "edition": "proto2", "fields": { "location": { "rule": "repeated", @@ -4854,12 +4865,18 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "span": { "rule": "repeated", "type": "int32", - "id": 2 + "id": 2, + "options": { + "packed": true + } }, "leadingComments": { "type": "string", @@ -4879,6 +4896,7 @@ } }, "GeneratedCodeInfo": { + "edition": "proto2", "fields": { "annotation": { "rule": "repeated", @@ -4892,7 +4910,10 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "sourceFile": { "type": "string", diff --git a/samples/commitAvroSchema.js b/samples/commitAvroSchema.js index b9a6eff73..3b302dee1 100644 --- a/samples/commitAvroSchema.js +++ b/samples/commitAvroSchema.js @@ -69,7 +69,7 @@ async function commitAvroSchema(schemaNameOrId, avscFile) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json' + avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json', ) { commitAvroSchema(schemaNameOrId, avscFile).catch(err => { console.error(err.message); diff --git a/samples/commitProtoSchema.js b/samples/commitProtoSchema.js index 997a1df45..15915b9db 100644 --- a/samples/commitProtoSchema.js +++ b/samples/commitProtoSchema.js @@ -69,7 +69,7 @@ async function commitProtoSchema(schemaNameOrId, protoFile) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers' + protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers', ) { commitProtoSchema(schemaNameOrId, protoFile).catch(err => { console.error(err.message); diff --git a/samples/createAvroSchema.js b/samples/createAvroSchema.js index 5de29cd4d..84b3bb660 100644 --- a/samples/createAvroSchema.js +++ b/samples/createAvroSchema.js @@ -49,7 +49,7 @@ async function createAvroSchema(schemaNameOrId, avscFile) { const schema = await pubSubClient.createSchema( schemaNameOrId, SchemaTypes.Avro, - definition + definition, ); const name = await schema.getName(); @@ -59,7 +59,7 @@ async function createAvroSchema(schemaNameOrId, avscFile) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json' + avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json', ) { createAvroSchema(schemaNameOrId, avscFile).catch(err => { console.error(err.message); diff --git a/samples/createBigQuerySubscription.js b/samples/createBigQuerySubscription.js index fc1da43dc..ddf90c364 100644 --- a/samples/createBigQuerySubscription.js +++ b/samples/createBigQuerySubscription.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function createBigQuerySubscription( topicNameOrId, subscriptionNameOrId, - bigqueryTableId + bigqueryTableId, ) { const options = { bigqueryConfig: { @@ -66,12 +66,12 @@ async function createBigQuerySubscription( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - bigqueryTableId = 'YOUR_TABLE_ID' + bigqueryTableId = 'YOUR_TABLE_ID', ) { createBigQuerySubscription( topicNameOrId, subscriptionNameOrId, - bigqueryTableId + bigqueryTableId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createProtoSchema.js b/samples/createProtoSchema.js index 23fc341ba..4c71af777 100644 --- a/samples/createProtoSchema.js +++ b/samples/createProtoSchema.js @@ -49,7 +49,7 @@ async function createProtoSchema(schemaNameOrId, protoFile) { const schema = await pubSubClient.createSchema( schemaNameOrId, SchemaTypes.ProtocolBuffer, - definition + definition, ); const fullName = await schema.getName(); @@ -59,7 +59,7 @@ async function createProtoSchema(schemaNameOrId, protoFile) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers' + protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers', ) { createProtoSchema(schemaNameOrId, protoFile).catch(err => { console.error(err.message); diff --git a/samples/createPushSubscription.js b/samples/createPushSubscription.js index aa9623e80..bd2d8aa01 100644 --- a/samples/createPushSubscription.js +++ b/samples/createPushSubscription.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function createPushSubscription( pushEndpoint, topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ) { const options = { pushConfig: { @@ -66,12 +66,12 @@ async function createPushSubscription( function main( pushEndpoint = 'YOUR_ENDPOINT_URL', topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createPushSubscription( pushEndpoint, topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createPushSubscriptionNoWrapper.js b/samples/createPushSubscriptionNoWrapper.js index fcf70cb6b..6b158d881 100644 --- a/samples/createPushSubscriptionNoWrapper.js +++ b/samples/createPushSubscriptionNoWrapper.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function createPushSubscriptionNoWrapper( pushEndpoint, topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ) { const options = { pushConfig: { @@ -72,12 +72,12 @@ async function createPushSubscriptionNoWrapper( function main( pushEndpoint = 'YOUR_ENDPOINT_URL', topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createPushSubscriptionNoWrapper( pushEndpoint, topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createSubscription.js b/samples/createSubscription.js index d0424fbf4..9b7c9311c 100644 --- a/samples/createSubscription.js +++ b/samples/createSubscription.js @@ -53,7 +53,7 @@ async function createSubscription(topicNameOrId, subscriptionNameOrId) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/createSubscriptionWithCloudStorage.js b/samples/createSubscriptionWithCloudStorage.js index bc75416cb..d2278f626 100644 --- a/samples/createSubscriptionWithCloudStorage.js +++ b/samples/createSubscriptionWithCloudStorage.js @@ -52,7 +52,7 @@ async function createCloudStorageSubscription( bucket, filenamePrefix, filenameSuffix, - maxDuration + maxDuration, ) { const options = { cloudStorageConfig: { @@ -70,7 +70,7 @@ async function createCloudStorageSubscription( .createSubscription(subscriptionName, options); console.log( - `Created subscription ${subscriptionName} with a cloud storage configuration.` + `Created subscription ${subscriptionName} with a cloud storage configuration.`, ); } // [END pubsub_create_cloud_storage_subscription] @@ -81,7 +81,7 @@ function main( bucket = 'YOUR_BUCKET_NAME', filenamePrefix = 'YOUR_FILENAME_PREFIX', filenameSuffix = 'YOUR_FILENAME_SUFFIX', - maxDuration = 60 + maxDuration = 60, ) { createCloudStorageSubscription( topicName, @@ -89,7 +89,7 @@ function main( bucket, filenamePrefix, filenameSuffix, - maxDuration + maxDuration, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createSubscriptionWithDeadLetterPolicy.js b/samples/createSubscriptionWithDeadLetterPolicy.js index 708efc18a..22da80285 100644 --- a/samples/createSubscriptionWithDeadLetterPolicy.js +++ b/samples/createSubscriptionWithDeadLetterPolicy.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithDeadLetterPolicy( topicNameOrId, subscriptionNameOrId, - deadLetterTopicNameOrId + deadLetterTopicNameOrId, ) { // Creates a new subscription const options = { @@ -59,10 +59,10 @@ async function createSubscriptionWithDeadLetterPolicy( .topic(topicNameOrId) .createSubscription(subscriptionNameOrId, options); console.log( - `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.` + `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.`, ); console.log( - 'To process dead letter messages, remember to add a subscription to your dead letter topic.' + 'To process dead letter messages, remember to add a subscription to your dead letter topic.', ); } // [END pubsub_dead_letter_create_subscription] @@ -70,12 +70,12 @@ async function createSubscriptionWithDeadLetterPolicy( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID' + deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID', ) { createSubscriptionWithDeadLetterPolicy( topicNameOrId, subscriptionNameOrId, - deadLetterTopicNameOrId + deadLetterTopicNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createSubscriptionWithExactlyOnceDelivery.js b/samples/createSubscriptionWithExactlyOnceDelivery.js index 6bbcb1422..a4f824467 100644 --- a/samples/createSubscriptionWithExactlyOnceDelivery.js +++ b/samples/createSubscriptionWithExactlyOnceDelivery.js @@ -44,7 +44,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithExactlyOnceDelivery( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ) { // Creates a new subscription await pubSubClient @@ -53,21 +53,21 @@ async function createSubscriptionWithExactlyOnceDelivery( enableExactlyOnceDelivery: true, }); console.log( - `Created subscription ${subscriptionNameOrId} with exactly-once delivery.` + `Created subscription ${subscriptionNameOrId} with exactly-once delivery.`, ); console.log( - 'To process messages, remember to check the return value of ackWithResponse().' + 'To process messages, remember to check the return value of ackWithResponse().', ); } // [END pubsub_create_subscription_with_exactly_once_delivery] function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscriptionWithExactlyOnceDelivery( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createSubscriptionWithFiltering.js b/samples/createSubscriptionWithFiltering.js index 9fddeadeb..8796a204e 100644 --- a/samples/createSubscriptionWithFiltering.js +++ b/samples/createSubscriptionWithFiltering.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithFilter( topicNameOrId, subscriptionNameOrId, - filterString + filterString, ) { // Creates a new subscription await pubSubClient @@ -55,7 +55,7 @@ async function createSubscriptionWithFilter( filter: filterString, }); console.log( - `Created subscription ${subscriptionNameOrId} with filter ${filterString}.` + `Created subscription ${subscriptionNameOrId} with filter ${filterString}.`, ); } // [END pubsub_create_subscription_with_filter] @@ -63,12 +63,12 @@ async function createSubscriptionWithFilter( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - filterString = 'YOUR_FILTER_STRING' + filterString = 'YOUR_FILTER_STRING', ) { createSubscriptionWithFilter( topicNameOrId, subscriptionNameOrId, - filterString + filterString, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createSubscriptionWithOrdering.js b/samples/createSubscriptionWithOrdering.js index 933260704..c8f8fa523 100644 --- a/samples/createSubscriptionWithOrdering.js +++ b/samples/createSubscriptionWithOrdering.js @@ -44,7 +44,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithOrdering( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ) { // Creates a new subscription await pubSubClient @@ -53,23 +53,23 @@ async function createSubscriptionWithOrdering( enableMessageOrdering: true, }); console.log( - `Created subscription ${subscriptionNameOrId} with ordering enabled.` + `Created subscription ${subscriptionNameOrId} with ordering enabled.`, ); console.log( - 'To process messages in order, remember to add an ordering key to your messages.' + 'To process messages in order, remember to add an ordering key to your messages.', ); } // [END pubsub_enable_subscription_ordering] function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscriptionWithOrdering(topicNameOrId, subscriptionNameOrId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/createSubscriptionWithRetryPolicy.js b/samples/createSubscriptionWithRetryPolicy.js index dfcc9b465..6b8273b5a 100644 --- a/samples/createSubscriptionWithRetryPolicy.js +++ b/samples/createSubscriptionWithRetryPolicy.js @@ -43,7 +43,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithRetryPolicy( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ) { // Creates a new subscription await pubSubClient @@ -59,19 +59,19 @@ async function createSubscriptionWithRetryPolicy( }, }); console.log( - `Created subscription ${subscriptionNameOrId} with retry policy.` + `Created subscription ${subscriptionNameOrId} with retry policy.`, ); } function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscriptionWithRetryPolicy(topicNameOrId, subscriptionNameOrId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/createTopic.js b/samples/createTopic.js index fe5308366..01db1ce53 100644 --- a/samples/createTopic.js +++ b/samples/createTopic.js @@ -48,7 +48,7 @@ async function createTopic(topicNameOrId) { } // [END pubsub_create_topic] -async function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { createTopic(topicNameOrId).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createTopicWithAwsMskIngestion.js b/samples/createTopicWithAwsMskIngestion.js index 5020e9be9..d9a1c463a 100644 --- a/samples/createTopicWithAwsMskIngestion.js +++ b/samples/createTopicWithAwsMskIngestion.js @@ -50,7 +50,7 @@ async function createTopicWithAwsMskIngestion( clusterArn, mskTopic, awsRoleArn, - gcpServiceAccount + gcpServiceAccount, ) { // Creates a new topic with AWS MSK ingestion. await pubSubClient.createTopic({ @@ -73,14 +73,14 @@ function main( clusterArn = 'arn:aws:kafka:...', mskTopic = 'YOUR_MSK_TOPIC', roleArn = 'arn:aws:iam:...', - gcpServiceAccount = 'ingestion-account@...' + gcpServiceAccount = 'ingestion-account@...', ) { createTopicWithAwsMskIngestion( topicNameOrId, clusterArn, mskTopic, roleArn, - gcpServiceAccount + gcpServiceAccount, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createTopicWithAzureEventHubsIngestion.js b/samples/createTopicWithAzureEventHubsIngestion.js index 1e4b16a72..ebc532917 100644 --- a/samples/createTopicWithAzureEventHubsIngestion.js +++ b/samples/createTopicWithAzureEventHubsIngestion.js @@ -56,7 +56,7 @@ async function createTopicWithAzureEventHubsIngestion( clientId, tenantId, subscriptionId, - gcpServiceAccount + gcpServiceAccount, ) { // Creates a new topic with Azure Event Hubs ingestion. await pubSubClient.createTopic({ @@ -74,7 +74,7 @@ async function createTopicWithAzureEventHubsIngestion( }, }); console.log( - `Topic ${topicNameOrId} created with Azure Event Hubs ingestion.` + `Topic ${topicNameOrId} created with Azure Event Hubs ingestion.`, ); } // [END pubsub_create_topic_with_azure_event_hubs_ingestion] @@ -87,7 +87,7 @@ function main( clientId = 'YOUR_CLIENT_ID', tenantId = 'YOUR_TENANT_ID', subscriptionId = 'YOUR_SUBSCRIPTION_ID', - gcpServiceAccount = 'ingestion-account@...' + gcpServiceAccount = 'ingestion-account@...', ) { createTopicWithAzureEventHubsIngestion( topicNameOrId, @@ -97,7 +97,7 @@ function main( clientId, tenantId, subscriptionId, - gcpServiceAccount + gcpServiceAccount, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createTopicWithCloudStorageIngestion.js b/samples/createTopicWithCloudStorageIngestion.js index c66beeb6d..beb1fd877 100644 --- a/samples/createTopicWithCloudStorageIngestion.js +++ b/samples/createTopicWithCloudStorageIngestion.js @@ -52,7 +52,7 @@ async function createTopicWithCloudStorageIngestion( inputFormat, textDelimiter, matchGlob, - minimumObjectCreateTime + minimumObjectCreateTime, ) { const minimumDate = Date.parse(minimumObjectCreateTime); const topicMetadata = { @@ -100,7 +100,7 @@ function main( inputFormat = 'text', textDelimiter = '\n', matchGlob = '**.txt', - minimumObjectCreateTime = 'YYYY-MM-DDThh:mm:ssZ' + minimumObjectCreateTime = 'YYYY-MM-DDThh:mm:ssZ', ) { createTopicWithCloudStorageIngestion( topicNameOrId, @@ -108,7 +108,7 @@ function main( inputFormat, textDelimiter, matchGlob, - minimumObjectCreateTime + minimumObjectCreateTime, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createTopicWithConfluentCloudIngestion.js b/samples/createTopicWithConfluentCloudIngestion.js index d81b53fd3..505ddd873 100644 --- a/samples/createTopicWithConfluentCloudIngestion.js +++ b/samples/createTopicWithConfluentCloudIngestion.js @@ -52,7 +52,7 @@ async function createTopicWithConfluentCloudIngestion( clusterId, confluentTopic, identityPoolId, - gcpServiceAccount + gcpServiceAccount, ) { // Creates a new topic with Confluent Cloud ingestion. await pubSubClient.createTopic({ @@ -77,7 +77,7 @@ function main( clusterId = 'YOUR_CLUSTER_ID', confluentTopic = 'YOUR_CONFLUENT_TOPIC', identityPoolId = 'pool-ID', - gcpServiceAccount = 'ingestion-account@...' + gcpServiceAccount = 'ingestion-account@...', ) { createTopicWithConfluentCloudIngestion( topicNameOrId, @@ -85,7 +85,7 @@ function main( clusterId, confluentTopic, identityPoolId, - gcpServiceAccount + gcpServiceAccount, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createTopicWithKinesisIngestion.js b/samples/createTopicWithKinesisIngestion.js index d9a50322e..73b4de57f 100644 --- a/samples/createTopicWithKinesisIngestion.js +++ b/samples/createTopicWithKinesisIngestion.js @@ -50,7 +50,7 @@ async function createTopicWithKinesisIngestion( awsRoleArn, gcpServiceAccount, streamArn, - consumerArn + consumerArn, ) { // Creates a new topic with Kinesis ingestion. await pubSubClient.createTopic({ @@ -73,14 +73,14 @@ function main( roleArn = 'arn:aws:iam:...', gcpServiceAccount = 'ingestion-account@...', streamArn = 'arn:aws:kinesis:...', - consumerArn = 'arn:aws:kinesis:...' + consumerArn = 'arn:aws:kinesis:...', ) { createTopicWithKinesisIngestion( topicNameOrId, roleArn, gcpServiceAccount, streamArn, - consumerArn + consumerArn, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/createTopicWithSchema.js b/samples/createTopicWithSchema.js index 7639fc432..f61f45bf6 100644 --- a/samples/createTopicWithSchema.js +++ b/samples/createTopicWithSchema.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function createTopicWithSchema( topicNameOrId, schemaNameOrId, - encodingType + encodingType, ) { // Get the fully qualified schema name. const schema = pubSubClient.schema(schemaNameOrId); @@ -68,13 +68,13 @@ async function createTopicWithSchema( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - encodingType = 'BINARY' + encodingType = 'BINARY', ) { createTopicWithSchema(topicNameOrId, schemaNameOrId, encodingType).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/createTopicWithSchemaRevisions.js b/samples/createTopicWithSchemaRevisions.js index 37934e736..1c4d5945d 100644 --- a/samples/createTopicWithSchemaRevisions.js +++ b/samples/createTopicWithSchemaRevisions.js @@ -50,7 +50,7 @@ async function createTopicWithSchemaRevisions( schemaNameOrId, encodingType, firstRevisionId, - lastRevisionId + lastRevisionId, ) { // Get the fully qualified schema name. const schema = pubSubClient.schema(schemaNameOrId); @@ -76,14 +76,14 @@ function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', encodingType = 'BINARY', firstRevisionId = 'YOUR_REVISION_ID', - lastRevisionId = 'YOUR_REVISION_ID' + lastRevisionId = 'YOUR_REVISION_ID', ) { createTopicWithSchemaRevisions( topicNameOrId, schemaNameOrId, encodingType, firstRevisionId, - lastRevisionId + lastRevisionId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/deleteSchemaRevision.js b/samples/deleteSchemaRevision.js index bbdafde15..24bd8176a 100644 --- a/samples/deleteSchemaRevision.js +++ b/samples/deleteSchemaRevision.js @@ -59,7 +59,7 @@ async function deleteSchemaRevision(schemaNameOrId, revisionId) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - revisionId = 'YOUR_REVISION_ID' + revisionId = 'YOUR_REVISION_ID', ) { deleteSchemaRevision(schemaNameOrId, revisionId).catch(err => { console.error(err.message); diff --git a/samples/detachSubscription.js b/samples/detachSubscription.js index 14b5c7bdc..fe5067984 100644 --- a/samples/detachSubscription.js +++ b/samples/detachSubscription.js @@ -46,7 +46,7 @@ async function detachSubscription(subscriptionNameOrId) { const sub = pubSubClient.subscription(subscriptionNameOrId); const [detached] = await sub.detached(); console.log( - `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}` + `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`, ); await pubSubClient.detachSubscription(subscriptionNameOrId); @@ -54,7 +54,7 @@ async function detachSubscription(subscriptionNameOrId) { const [updatedDetached] = await sub.detached(); console.log( - `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}` + `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`, ); } // [END pubsub_detach_subscription] diff --git a/samples/getSchemaRevision.js b/samples/getSchemaRevision.js index 8cb5278b7..72fd67047 100644 --- a/samples/getSchemaRevision.js +++ b/samples/getSchemaRevision.js @@ -53,14 +53,14 @@ async function getSchemaRevision(schemaNameOrId, revisionId) { }); console.log( - `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.` + `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.`, ); } // [END pubsub_get_schema_revision] function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - revisionId = 'YOUR_REVISION_ID' + revisionId = 'YOUR_REVISION_ID', ) { getSchemaRevision(schemaNameOrId, revisionId).catch(err => { console.error(err.message); diff --git a/samples/listenForAvroRecords.js b/samples/listenForAvroRecords.js index 10ff478fa..e16653452 100644 --- a/samples/listenForAvroRecords.js +++ b/samples/listenForAvroRecords.js @@ -98,7 +98,7 @@ function listenForAvroRecords(subscriptionNameOrId, timeout) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); diff --git a/samples/listenForAvroRecordsWithRevisions.js b/samples/listenForAvroRecordsWithRevisions.js index a4a46bf8d..cf4e39156 100644 --- a/samples/listenForAvroRecordsWithRevisions.js +++ b/samples/listenForAvroRecordsWithRevisions.js @@ -48,7 +48,7 @@ const pubSubClient = new PubSub(); async function listenForAvroRecordsWithRevisions( subscriptionNameOrId, - timeout + timeout, ) { // References an existing subscription const subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -104,7 +104,7 @@ async function listenForAvroRecordsWithRevisions( console.log(`\tData: ${JSON.stringify(result, null, 4)}`); console.log(`\tAttributes: ${message.attributes}`); console.log( - `\tProvince ${result.name} is abbreviated as ${result.post_abbr}` + `\tProvince ${result.name} is abbreviated as ${result.post_abbr}`, ); messageCount += 1; @@ -124,7 +124,7 @@ async function listenForAvroRecordsWithRevisions( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); @@ -132,7 +132,7 @@ function main( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/listenForErrors.js b/samples/listenForErrors.js index 75f1c1bae..8e1be3024 100644 --- a/samples/listenForErrors.js +++ b/samples/listenForErrors.js @@ -76,7 +76,7 @@ function listenForErrors(subscriptionNameOrId, timeout) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 10 + timeout = 10, ) { timeout = Number(timeout); listenForErrors(subscriptionNameOrId, timeout); diff --git a/samples/listenForMessages.js b/samples/listenForMessages.js index ebfdbbeb7..f9e5cc17b 100644 --- a/samples/listenForMessages.js +++ b/samples/listenForMessages.js @@ -74,7 +74,7 @@ function listenForMessages(subscriptionNameOrId, timeout) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); listenForMessages(subscriptionNameOrId, timeout); diff --git a/samples/listenForMessagesWithExactlyOnceDelivery.js b/samples/listenForMessagesWithExactlyOnceDelivery.js index a5d549f84..c933ded55 100644 --- a/samples/listenForMessagesWithExactlyOnceDelivery.js +++ b/samples/listenForMessagesWithExactlyOnceDelivery.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub({ async function listenForMessagesWithExactlyOnceDelivery( subscriptionNameOrId, - timeout + timeout, ) { // References an existing subscription const subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -75,7 +75,7 @@ async function listenForMessagesWithExactlyOnceDelivery( // is only for permanent failures; transient errors are retried automatically. const ackError = e; console.log( - `Ack for message ${message.id} failed with error: ${ackError.errorCode}` + `Ack for message ${message.id} failed with error: ${ackError.errorCode}`, ); } }; @@ -92,11 +92,11 @@ async function listenForMessagesWithExactlyOnceDelivery( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { listenForMessagesWithExactlyOnceDelivery( subscriptionNameOrId, - Number(timeout) + Number(timeout), ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/listenForProtobufMessages.js b/samples/listenForProtobufMessages.js index 933797fb2..f6abb6e15 100644 --- a/samples/listenForProtobufMessages.js +++ b/samples/listenForProtobufMessages.js @@ -100,7 +100,7 @@ async function listenForProtobufMessages(subscriptionNameOrId, timeout) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); diff --git a/samples/listenWithCustomAttributes.js b/samples/listenWithCustomAttributes.js index b231d431f..0a3a8e84c 100644 --- a/samples/listenWithCustomAttributes.js +++ b/samples/listenWithCustomAttributes.js @@ -51,7 +51,7 @@ async function listenWithCustomAttributes(subscriptionNameOrId, timeout) { console.log( `Received message: id ${message.id}, data ${ message.data - }, attributes: ${JSON.stringify(message.attributes)}` + }, attributes: ${JSON.stringify(message.attributes)}`, ); // "Ack" (acknowledge receipt of) the message @@ -66,9 +66,9 @@ async function listenWithCustomAttributes(subscriptionNameOrId, timeout) { } // [END pubsub_subscriber_async_pull_custom_attributes] -async function main( +function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); listenWithCustomAttributes(subscriptionNameOrId, timeout).catch(err => { diff --git a/samples/listenWithOpenTelemetryTracing.js b/samples/listenWithOpenTelemetryTracing.js index 55178dde5..7b8d6bc34 100644 --- a/samples/listenWithOpenTelemetryTracing.js +++ b/samples/listenWithOpenTelemetryTracing.js @@ -119,7 +119,7 @@ async function subscriptionListen(subscriptionNameOrId) { subscriber.removeAllListeners(); await shutdown(); r(); - }, SUBSCRIBER_TIMEOUT * 1000) + }, SUBSCRIBER_TIMEOUT * 1000), ); } // [END pubsub_subscribe_otel_tracing] diff --git a/samples/modifyPushConfig.js b/samples/modifyPushConfig.js index df35aa7d9..8f0fd9289 100644 --- a/samples/modifyPushConfig.js +++ b/samples/modifyPushConfig.js @@ -59,7 +59,7 @@ async function modifyPushConfig(topicNameOrId, subscriptionNameOrId) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { modifyPushConfig(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/optimisticSubscribe.js b/samples/optimisticSubscribe.js index 758410d60..0bc7b59b8 100644 --- a/samples/optimisticSubscribe.js +++ b/samples/optimisticSubscribe.js @@ -67,7 +67,7 @@ function optimisticSubscribe(subscriptionNameOrId, topicNameOrId, timeout) { console.log('Subscription not found, creating it'); await pubSubClient.createSubscription( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ); // Refresh our subscriber object and re-attach the message handler. @@ -92,7 +92,7 @@ function optimisticSubscribe(subscriptionNameOrId, topicNameOrId, timeout) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); optimisticSubscribe(subscriptionNameOrId, topicNameOrId, timeout); diff --git a/samples/package.json b/samples/package.json index fe8ca021c..b7ade629e 100644 --- a/samples/package.json +++ b/samples/package.json @@ -9,7 +9,7 @@ "author": "Google Inc.", "repository": "googleapis/nodejs-pubsub", "engines": { - "node": ">=12.0.0" + "node": ">=18" }, "scripts": { "test": "mocha build/system-test --timeout 600000", @@ -18,7 +18,10 @@ "sampletsc": "cd typescript && tsc -p . && cd ..", "compile": "npm run tsc && npm run sampletsc", "clean": "gts clean && rm -rf build/", - "precompile": "npm run clean" + "precompile": "npm run clean", + "pretypeless": "npx eslint --fix typescript/*.ts", + "typeless": "npx typeless-sample-bot --outputpath . --targets typescript --recursive", + "posttypeless": "npx eslint --fix *.js" }, "dependencies": { "@google-cloud/opentelemetry-cloud-trace-exporter": "^2.0.0", @@ -35,6 +38,7 @@ }, "devDependencies": { "@google-cloud/bigquery": "^7.0.0", + "@google-cloud/typeless-sample-bot": "^3.0.0", "@types/chai": "^4.2.16", "chai": "^4.2.0", "gts": "^5.0.0", @@ -44,4 +48,4 @@ "typescript": "^5.1.6", "uuid": "^9.0.0" } -} +} \ No newline at end of file diff --git a/samples/publishBatchedMessages.js b/samples/publishBatchedMessages.js index a5f99b242..73674c473 100644 --- a/samples/publishBatchedMessages.js +++ b/samples/publishBatchedMessages.js @@ -48,7 +48,7 @@ async function publishBatchedMessages( topicNameOrId, data, maxMessages, - maxWaitTime + maxWaitTime, ) { // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) const dataBuffer = Buffer.from(data); @@ -70,7 +70,7 @@ async function publishBatchedMessages( data: dataBuffer, }); console.log(`Message ${messageId} published.`); - })() + })(), ); } await Promise.all(promises); @@ -81,7 +81,7 @@ function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', data = JSON.stringify({foo: 'bar'}), maxMessages = 10, - maxWaitTime = 10 + maxWaitTime = 10, ) { maxMessages = Number(maxMessages); maxWaitTime = Number(maxWaitTime); @@ -89,7 +89,7 @@ function main( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/publishMessage.js b/samples/publishMessage.js index 6b0581d08..a2b71cf13 100644 --- a/samples/publishMessage.js +++ b/samples/publishMessage.js @@ -63,7 +63,7 @@ async function publishMessage(topicNameOrId, data) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) + data = JSON.stringify({foo: 'bar'}), ) { publishMessage(topicNameOrId, data).catch(err => { console.error(err.message); diff --git a/samples/publishMessageWithCustomAttributes.js b/samples/publishMessageWithCustomAttributes.js index 224a9ce0d..83378f184 100644 --- a/samples/publishMessageWithCustomAttributes.js +++ b/samples/publishMessageWithCustomAttributes.js @@ -65,7 +65,7 @@ async function publishMessageWithCustomAttributes(topicNameOrId, data) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) + data = JSON.stringify({foo: 'bar'}), ) { publishMessageWithCustomAttributes(topicNameOrId, data).catch(console.error); } diff --git a/samples/publishOrderedMessage.js b/samples/publishOrderedMessage.js index 19761b6ad..b34d36c63 100644 --- a/samples/publishOrderedMessage.js +++ b/samples/publishOrderedMessage.js @@ -80,12 +80,12 @@ async function publishOrderedMessage(topicNameOrId, data, orderingKey) { } // [END pubsub_publish_with_ordering_keys] -async function main( +function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', data = JSON.stringify({foo: 'bar'}), - orderingKey = 'key1' + orderingKey = 'key1', ) { - await publishOrderedMessage(topicNameOrId, data, orderingKey).catch(err => { + publishOrderedMessage(topicNameOrId, data, orderingKey).catch(err => { console.error(err.message); process.exitCode = 1; }); diff --git a/samples/publishWithRetrySettings.js b/samples/publishWithRetrySettings.js index 24738b7e0..f5c380490 100644 --- a/samples/publishWithRetrySettings.js +++ b/samples/publishWithRetrySettings.js @@ -102,7 +102,7 @@ async function publishWithRetrySettings(topicNameOrId, data) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) + data = JSON.stringify({foo: 'bar'}), ) { publishWithRetrySettings(topicNameOrId, data).catch(err => { console.error(err.message); diff --git a/samples/quickstart.js b/samples/quickstart.js index b1f296929..56df336f3 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -30,7 +30,7 @@ const {PubSub} = require('@google-cloud/pubsub'); async function quickstart( projectId = 'your-project-id', // Your Google Cloud Platform project ID topicNameOrId = 'my-topic', // Name for the new topic to create - subscriptionName = 'my-sub' // Name for the new subscription to create + subscriptionName = 'my-sub', // Name for the new subscription to create ) { // Instantiates a client const pubsub = new PubSub({projectId}); @@ -55,12 +55,11 @@ async function quickstart( }); // Send a message to the topic - topic.publishMessage({data: Buffer.from('Test message!')}); + await topic.publishMessage({data: Buffer.from('Test message!')}); } // [END pubsub_quickstart_create_topic] -process.on('unhandledRejection', err => { +quickstart(...process.argv.slice(2)).catch(err => { console.error(err.message); process.exitCode = 1; }); -quickstart(...process.argv.slice(2)); diff --git a/samples/removeDeadLetterPolicy.js b/samples/removeDeadLetterPolicy.js index 3268678ab..9667ecebb 100644 --- a/samples/removeDeadLetterPolicy.js +++ b/samples/removeDeadLetterPolicy.js @@ -53,14 +53,14 @@ async function removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId) { .setMetadata(metadata); console.log( - `Removed dead letter topic from ${subscriptionNameOrId} subscription.` + `Removed dead letter topic from ${subscriptionNameOrId} subscription.`, ); } // [END pubsub_dead_letter_remove] function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/resumePublish.js b/samples/resumePublish.js index 5d66e712f..d471a3adc 100644 --- a/samples/resumePublish.js +++ b/samples/resumePublish.js @@ -80,7 +80,7 @@ async function resumePublish(topicNameOrId, data, orderingKey) { async function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', data = JSON.stringify({foo: 'bar'}), - orderingKey = 'key1' + orderingKey = 'key1', ) { return await resumePublish(topicNameOrId, data, orderingKey).catch(err => { console.error(err.message); diff --git a/samples/rollbackSchema.js b/samples/rollbackSchema.js index ae5d8fc3f..32285797f 100644 --- a/samples/rollbackSchema.js +++ b/samples/rollbackSchema.js @@ -60,7 +60,7 @@ async function rollbackSchema(schemaNameOrId, revisionId) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - revisionId = 'YOUR_REVISION_ID' + revisionId = 'YOUR_REVISION_ID', ) { rollbackSchema(schemaNameOrId, revisionId).catch(err => { console.error(err.message); diff --git a/samples/subscribeWithFlowControlSettings.js b/samples/subscribeWithFlowControlSettings.js index 367d701c2..f9d8cd05f 100644 --- a/samples/subscribeWithFlowControlSettings.js +++ b/samples/subscribeWithFlowControlSettings.js @@ -48,7 +48,7 @@ const pubSubClient = new PubSub(); async function subscribeWithFlowControlSettings( subscriptionNameOrId, maxInProgress, - timeout + timeout, ) { const subscriberOptions = { flowControl: { @@ -60,11 +60,11 @@ async function subscribeWithFlowControlSettings( // Note that flow control settings are not persistent across subscribers. const subscription = pubSubClient.subscription( subscriptionNameOrId, - subscriberOptions + subscriberOptions, ); console.log( - `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.` + `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.`, ); const messageHandler = message => { @@ -79,8 +79,8 @@ async function subscribeWithFlowControlSettings( subscription.on('message', messageHandler); // Wait a while for the subscription to run. (Part of the sample only.) - setTimeout(() => { - subscription.close(); + setTimeout(async () => { + await subscription.close(); }, timeout * 1000); } // [END pubsub_subscriber_flow_settings] @@ -88,7 +88,7 @@ async function subscribeWithFlowControlSettings( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', maxInProgress = 1, - timeout = 10 + timeout = 10, ) { maxInProgress = Number(maxInProgress); timeout = Number(timeout); @@ -96,7 +96,7 @@ function main( subscribeWithFlowControlSettings( subscriptionNameOrId, maxInProgress, - timeout + timeout, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/synchronousPull.js b/samples/synchronousPull.js index 755143ebe..2fc522ba8 100644 --- a/samples/synchronousPull.js +++ b/samples/synchronousPull.js @@ -86,7 +86,7 @@ async function synchronousPull(projectId, subscriptionNameOrId) { function main( projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { synchronousPull(projectId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/synchronousPullWithDeliveryAttempts.js b/samples/synchronousPullWithDeliveryAttempts.js index 40c76bdc1..2fb621d21 100644 --- a/samples/synchronousPullWithDeliveryAttempts.js +++ b/samples/synchronousPullWithDeliveryAttempts.js @@ -45,7 +45,7 @@ const subClient = new v1.SubscriberClient(); async function synchronousPullWithDeliveryAttempts( projectId, - subscriptionNameOrId + subscriptionNameOrId, ) { // The low level API client requires a name only. const formattedSubscription = @@ -87,13 +87,13 @@ async function synchronousPullWithDeliveryAttempts( function main( projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { synchronousPullWithDeliveryAttempts(projectId, subscriptionNameOrId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/synchronousPullWithLeaseManagement.js b/samples/synchronousPullWithLeaseManagement.js index 5a254e765..e6d83c476 100644 --- a/samples/synchronousPullWithLeaseManagement.js +++ b/samples/synchronousPullWithLeaseManagement.js @@ -29,7 +29,7 @@ function main( projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { // [START pubsub_subscriber_sync_pull_with_lease] /** @@ -113,7 +113,7 @@ function main( await subClient.modifyAckDeadline(modifyAckRequest); console.log( - `Reset ack deadline for "${message.message.data}" for ${newAckDeadlineSeconds}s.` + `Reset ack deadline for "${message.message.data}" for ${newAckDeadlineSeconds}s.`, ); } } diff --git a/samples/system-test/schema.test.ts b/samples/system-test/schema.test.ts index 21e0753c7..69add231b 100644 --- a/samples/system-test/schema.test.ts +++ b/samples/system-test/schema.test.ts @@ -31,8 +31,6 @@ import * as defer from 'p-defer'; import {TestResources} from './testResources'; import {commandFor} from './common'; -// Tests run as Node 14. -// eslint-disable-next-line n/no-unsupported-features/node-builtins import {promises as fs} from 'fs'; const execSync = (cmd: string) => cp.execSync(cmd, {encoding: 'utf-8'}); diff --git a/samples/tsconfig.json b/samples/tsconfig.json index 5923963b4..8b56b5c4c 100644 --- a/samples/tsconfig.json +++ b/samples/tsconfig.json @@ -11,9 +11,7 @@ "moduleResolution": "node" }, "include": [ - "system-test/*.ts" - ], - "exclude": [ - "typescript/" + "system-test/*.ts", + "typescript/*.ts" ] } diff --git a/samples/typescript/commitAvroSchema.ts b/samples/typescript/commitAvroSchema.ts index 983aab6c0..4ae374231 100644 --- a/samples/typescript/commitAvroSchema.ts +++ b/samples/typescript/commitAvroSchema.ts @@ -65,7 +65,7 @@ async function commitAvroSchema(schemaNameOrId: string, avscFile: string) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json' + avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json', ) { commitAvroSchema(schemaNameOrId, avscFile).catch(err => { console.error(err.message); diff --git a/samples/typescript/commitProtoSchema.ts b/samples/typescript/commitProtoSchema.ts index b540ed98e..8fc0e4a6e 100644 --- a/samples/typescript/commitProtoSchema.ts +++ b/samples/typescript/commitProtoSchema.ts @@ -65,7 +65,7 @@ async function commitProtoSchema(schemaNameOrId: string, protoFile: string) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers' + protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers', ) { commitProtoSchema(schemaNameOrId, protoFile).catch(err => { console.error(err.message); diff --git a/samples/typescript/createAvroSchema.ts b/samples/typescript/createAvroSchema.ts index dab58797f..4cb2f3028 100644 --- a/samples/typescript/createAvroSchema.ts +++ b/samples/typescript/createAvroSchema.ts @@ -45,7 +45,7 @@ async function createAvroSchema(schemaNameOrId: string, avscFile: string) { const schema = await pubSubClient.createSchema( schemaNameOrId, SchemaTypes.Avro, - definition + definition, ); const name = await schema.getName(); @@ -55,7 +55,7 @@ async function createAvroSchema(schemaNameOrId: string, avscFile: string) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json' + avscFile = 'path/to/an/avro/schema/file/(.avsc)/formatted/in/json', ) { createAvroSchema(schemaNameOrId, avscFile).catch(err => { console.error(err.message); diff --git a/samples/typescript/createBigQuerySubscription.ts b/samples/typescript/createBigQuerySubscription.ts index 6b109e5e7..78da9af69 100644 --- a/samples/typescript/createBigQuerySubscription.ts +++ b/samples/typescript/createBigQuerySubscription.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function createBigQuerySubscription( topicNameOrId: string, subscriptionNameOrId: string, - bigqueryTableId: string + bigqueryTableId: string, ) { const options: CreateSubscriptionOptions = { bigqueryConfig: { @@ -62,12 +62,12 @@ async function createBigQuerySubscription( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - bigqueryTableId = 'YOUR_TABLE_ID' + bigqueryTableId = 'YOUR_TABLE_ID', ) { createBigQuerySubscription( topicNameOrId, subscriptionNameOrId, - bigqueryTableId + bigqueryTableId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createProtoSchema.ts b/samples/typescript/createProtoSchema.ts index a75525885..e315b1336 100644 --- a/samples/typescript/createProtoSchema.ts +++ b/samples/typescript/createProtoSchema.ts @@ -45,7 +45,7 @@ async function createProtoSchema(schemaNameOrId: string, protoFile: string) { const schema = await pubSubClient.createSchema( schemaNameOrId, SchemaTypes.ProtocolBuffer, - definition + definition, ); const fullName: string = await schema.getName(); @@ -55,7 +55,7 @@ async function createProtoSchema(schemaNameOrId: string, protoFile: string) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers' + protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers', ) { createProtoSchema(schemaNameOrId, protoFile).catch(err => { console.error(err.message); diff --git a/samples/typescript/createPushSubscription.ts b/samples/typescript/createPushSubscription.ts index bc36cf782..dccef02fd 100644 --- a/samples/typescript/createPushSubscription.ts +++ b/samples/typescript/createPushSubscription.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function createPushSubscription( pushEndpoint: string, topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { const options: CreateSubscriptionOptions = { pushConfig: { @@ -62,12 +62,12 @@ async function createPushSubscription( function main( pushEndpoint = 'YOUR_ENDPOINT_URL', topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createPushSubscription( pushEndpoint, topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createPushSubscriptionNoWrapper.ts b/samples/typescript/createPushSubscriptionNoWrapper.ts index 550688d59..6070ceeba 100644 --- a/samples/typescript/createPushSubscriptionNoWrapper.ts +++ b/samples/typescript/createPushSubscriptionNoWrapper.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function createPushSubscriptionNoWrapper( pushEndpoint: string, topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { const options: CreateSubscriptionOptions = { pushConfig: { @@ -68,12 +68,12 @@ async function createPushSubscriptionNoWrapper( function main( pushEndpoint = 'YOUR_ENDPOINT_URL', topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createPushSubscriptionNoWrapper( pushEndpoint, topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createSubscription.ts b/samples/typescript/createSubscription.ts index 61303448f..b5f04dde0 100644 --- a/samples/typescript/createSubscription.ts +++ b/samples/typescript/createSubscription.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function createSubscription( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { // Creates a new subscription await pubSubClient @@ -52,7 +52,7 @@ async function createSubscription( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/typescript/createSubscriptionWithCloudStorage.ts b/samples/typescript/createSubscriptionWithCloudStorage.ts index 9f6cafce2..e9edf5111 100644 --- a/samples/typescript/createSubscriptionWithCloudStorage.ts +++ b/samples/typescript/createSubscriptionWithCloudStorage.ts @@ -48,7 +48,7 @@ async function createCloudStorageSubscription( bucket: string, filenamePrefix: string, filenameSuffix: string, - maxDuration: number + maxDuration: number, ) { const options: CreateSubscriptionOptions = { cloudStorageConfig: { @@ -66,7 +66,7 @@ async function createCloudStorageSubscription( .createSubscription(subscriptionName, options); console.log( - `Created subscription ${subscriptionName} with a cloud storage configuration.` + `Created subscription ${subscriptionName} with a cloud storage configuration.`, ); } // [END pubsub_create_cloud_storage_subscription] @@ -77,7 +77,7 @@ function main( bucket = 'YOUR_BUCKET_NAME', filenamePrefix = 'YOUR_FILENAME_PREFIX', filenameSuffix = 'YOUR_FILENAME_SUFFIX', - maxDuration = 60 + maxDuration = 60, ) { createCloudStorageSubscription( topicName, @@ -85,7 +85,7 @@ function main( bucket, filenamePrefix, filenameSuffix, - maxDuration + maxDuration, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts b/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts index e2f8f12f3..ef00e7175 100644 --- a/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts +++ b/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithDeadLetterPolicy( topicNameOrId: string, subscriptionNameOrId: string, - deadLetterTopicNameOrId: string + deadLetterTopicNameOrId: string, ) { // Creates a new subscription const options: CreateSubscriptionOptions = { @@ -55,10 +55,10 @@ async function createSubscriptionWithDeadLetterPolicy( .topic(topicNameOrId) .createSubscription(subscriptionNameOrId, options); console.log( - `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.` + `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.`, ); console.log( - 'To process dead letter messages, remember to add a subscription to your dead letter topic.' + 'To process dead letter messages, remember to add a subscription to your dead letter topic.', ); } // [END pubsub_dead_letter_create_subscription] @@ -66,12 +66,12 @@ async function createSubscriptionWithDeadLetterPolicy( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID' + deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID', ) { createSubscriptionWithDeadLetterPolicy( topicNameOrId, subscriptionNameOrId, - deadLetterTopicNameOrId + deadLetterTopicNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createSubscriptionWithExactlyOnceDelivery.ts b/samples/typescript/createSubscriptionWithExactlyOnceDelivery.ts index 472006fea..e56b7d164 100644 --- a/samples/typescript/createSubscriptionWithExactlyOnceDelivery.ts +++ b/samples/typescript/createSubscriptionWithExactlyOnceDelivery.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithExactlyOnceDelivery( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { // Creates a new subscription await pubSubClient @@ -49,21 +49,21 @@ async function createSubscriptionWithExactlyOnceDelivery( enableExactlyOnceDelivery: true, }); console.log( - `Created subscription ${subscriptionNameOrId} with exactly-once delivery.` + `Created subscription ${subscriptionNameOrId} with exactly-once delivery.`, ); console.log( - 'To process messages, remember to check the return value of ackWithResponse().' + 'To process messages, remember to check the return value of ackWithResponse().', ); } // [END pubsub_create_subscription_with_exactly_once_delivery] function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscriptionWithExactlyOnceDelivery( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createSubscriptionWithFiltering.ts b/samples/typescript/createSubscriptionWithFiltering.ts index d497027b8..573d0c0da 100644 --- a/samples/typescript/createSubscriptionWithFiltering.ts +++ b/samples/typescript/createSubscriptionWithFiltering.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithFilter( topicNameOrId: string, subscriptionNameOrId: string, - filterString: string + filterString: string, ) { // Creates a new subscription await pubSubClient @@ -51,7 +51,7 @@ async function createSubscriptionWithFilter( filter: filterString, }); console.log( - `Created subscription ${subscriptionNameOrId} with filter ${filterString}.` + `Created subscription ${subscriptionNameOrId} with filter ${filterString}.`, ); } // [END pubsub_create_subscription_with_filter] @@ -59,12 +59,12 @@ async function createSubscriptionWithFilter( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - filterString = 'YOUR_FILTER_STRING' + filterString = 'YOUR_FILTER_STRING', ) { createSubscriptionWithFilter( topicNameOrId, subscriptionNameOrId, - filterString + filterString, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createSubscriptionWithOrdering.ts b/samples/typescript/createSubscriptionWithOrdering.ts index 51bc67f9a..b65078292 100644 --- a/samples/typescript/createSubscriptionWithOrdering.ts +++ b/samples/typescript/createSubscriptionWithOrdering.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithOrdering( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { // Creates a new subscription await pubSubClient @@ -49,23 +49,23 @@ async function createSubscriptionWithOrdering( enableMessageOrdering: true, }); console.log( - `Created subscription ${subscriptionNameOrId} with ordering enabled.` + `Created subscription ${subscriptionNameOrId} with ordering enabled.`, ); console.log( - 'To process messages in order, remember to add an ordering key to your messages.' + 'To process messages in order, remember to add an ordering key to your messages.', ); } // [END pubsub_enable_subscription_ordering] function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscriptionWithOrdering(topicNameOrId, subscriptionNameOrId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/typescript/createSubscriptionWithRetryPolicy.ts b/samples/typescript/createSubscriptionWithRetryPolicy.ts index fc709614f..81ffc170e 100644 --- a/samples/typescript/createSubscriptionWithRetryPolicy.ts +++ b/samples/typescript/createSubscriptionWithRetryPolicy.ts @@ -39,7 +39,7 @@ const pubSubClient = new PubSub(); async function createSubscriptionWithRetryPolicy( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { // Creates a new subscription await pubSubClient @@ -55,19 +55,19 @@ async function createSubscriptionWithRetryPolicy( }, }); console.log( - `Created subscription ${subscriptionNameOrId} with retry policy.` + `Created subscription ${subscriptionNameOrId} with retry policy.`, ); } function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { createSubscriptionWithRetryPolicy(topicNameOrId, subscriptionNameOrId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/typescript/createTopic.ts b/samples/typescript/createTopic.ts index 04e26baf3..b060e9894 100644 --- a/samples/typescript/createTopic.ts +++ b/samples/typescript/createTopic.ts @@ -44,7 +44,7 @@ async function createTopic(topicNameOrId: string) { } // [END pubsub_create_topic] -async function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { createTopic(topicNameOrId).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createTopicWithAwsMskIngestion.ts b/samples/typescript/createTopicWithAwsMskIngestion.ts index 117ddb3c6..7b70c9a78 100644 --- a/samples/typescript/createTopicWithAwsMskIngestion.ts +++ b/samples/typescript/createTopicWithAwsMskIngestion.ts @@ -46,7 +46,7 @@ async function createTopicWithAwsMskIngestion( clusterArn: string, mskTopic: string, awsRoleArn: string, - gcpServiceAccount: string + gcpServiceAccount: string, ) { // Creates a new topic with AWS MSK ingestion. await pubSubClient.createTopic({ @@ -69,14 +69,14 @@ function main( clusterArn = 'arn:aws:kafka:...', mskTopic = 'YOUR_MSK_TOPIC', roleArn = 'arn:aws:iam:...', - gcpServiceAccount = 'ingestion-account@...' + gcpServiceAccount = 'ingestion-account@...', ) { createTopicWithAwsMskIngestion( topicNameOrId, clusterArn, mskTopic, roleArn, - gcpServiceAccount + gcpServiceAccount, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createTopicWithAzureEventHubsIngestion.ts b/samples/typescript/createTopicWithAzureEventHubsIngestion.ts index e49a4bf3d..6c8988a54 100644 --- a/samples/typescript/createTopicWithAzureEventHubsIngestion.ts +++ b/samples/typescript/createTopicWithAzureEventHubsIngestion.ts @@ -52,7 +52,7 @@ async function createTopicWithAzureEventHubsIngestion( clientId: string, tenantId: string, subscriptionId: string, - gcpServiceAccount: string + gcpServiceAccount: string, ) { // Creates a new topic with Azure Event Hubs ingestion. await pubSubClient.createTopic({ @@ -70,7 +70,7 @@ async function createTopicWithAzureEventHubsIngestion( }, }); console.log( - `Topic ${topicNameOrId} created with Azure Event Hubs ingestion.` + `Topic ${topicNameOrId} created with Azure Event Hubs ingestion.`, ); } // [END pubsub_create_topic_with_azure_event_hubs_ingestion] @@ -83,7 +83,7 @@ function main( clientId = 'YOUR_CLIENT_ID', tenantId = 'YOUR_TENANT_ID', subscriptionId = 'YOUR_SUBSCRIPTION_ID', - gcpServiceAccount = 'ingestion-account@...' + gcpServiceAccount = 'ingestion-account@...', ) { createTopicWithAzureEventHubsIngestion( topicNameOrId, @@ -93,7 +93,7 @@ function main( clientId, tenantId, subscriptionId, - gcpServiceAccount + gcpServiceAccount, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createTopicWithCloudStorageIngestion.ts b/samples/typescript/createTopicWithCloudStorageIngestion.ts index c30035bba..a9c1b2e38 100644 --- a/samples/typescript/createTopicWithCloudStorageIngestion.ts +++ b/samples/typescript/createTopicWithCloudStorageIngestion.ts @@ -48,7 +48,7 @@ async function createTopicWithCloudStorageIngestion( inputFormat: string, textDelimiter: string, matchGlob: string, - minimumObjectCreateTime: string + minimumObjectCreateTime: string, ) { const minimumDate = Date.parse(minimumObjectCreateTime); const topicMetadata: TopicMetadata = { @@ -96,7 +96,7 @@ function main( inputFormat = 'text', textDelimiter = '\n', matchGlob = '**.txt', - minimumObjectCreateTime = 'YYYY-MM-DDThh:mm:ssZ' + minimumObjectCreateTime = 'YYYY-MM-DDThh:mm:ssZ', ) { createTopicWithCloudStorageIngestion( topicNameOrId, @@ -104,7 +104,7 @@ function main( inputFormat, textDelimiter, matchGlob, - minimumObjectCreateTime + minimumObjectCreateTime, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createTopicWithConfluentCloudIngestion.ts b/samples/typescript/createTopicWithConfluentCloudIngestion.ts index a540dbdad..5df168e0e 100644 --- a/samples/typescript/createTopicWithConfluentCloudIngestion.ts +++ b/samples/typescript/createTopicWithConfluentCloudIngestion.ts @@ -48,7 +48,7 @@ async function createTopicWithConfluentCloudIngestion( clusterId: string, confluentTopic: string, identityPoolId: string, - gcpServiceAccount: string + gcpServiceAccount: string, ) { // Creates a new topic with Confluent Cloud ingestion. await pubSubClient.createTopic({ @@ -73,7 +73,7 @@ function main( clusterId = 'YOUR_CLUSTER_ID', confluentTopic = 'YOUR_CONFLUENT_TOPIC', identityPoolId = 'pool-ID', - gcpServiceAccount = 'ingestion-account@...' + gcpServiceAccount = 'ingestion-account@...', ) { createTopicWithConfluentCloudIngestion( topicNameOrId, @@ -81,7 +81,7 @@ function main( clusterId, confluentTopic, identityPoolId, - gcpServiceAccount + gcpServiceAccount, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createTopicWithKinesisIngestion.ts b/samples/typescript/createTopicWithKinesisIngestion.ts index 6b42d4dc1..4b34099b4 100644 --- a/samples/typescript/createTopicWithKinesisIngestion.ts +++ b/samples/typescript/createTopicWithKinesisIngestion.ts @@ -46,7 +46,7 @@ async function createTopicWithKinesisIngestion( awsRoleArn: string, gcpServiceAccount: string, streamArn: string, - consumerArn: string + consumerArn: string, ) { // Creates a new topic with Kinesis ingestion. await pubSubClient.createTopic({ @@ -69,14 +69,14 @@ function main( roleArn = 'arn:aws:iam:...', gcpServiceAccount = 'ingestion-account@...', streamArn = 'arn:aws:kinesis:...', - consumerArn = 'arn:aws:kinesis:...' + consumerArn = 'arn:aws:kinesis:...', ) { createTopicWithKinesisIngestion( topicNameOrId, roleArn, gcpServiceAccount, streamArn, - consumerArn + consumerArn, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/createTopicWithSchema.ts b/samples/typescript/createTopicWithSchema.ts index 94231bf69..9e005a9e3 100644 --- a/samples/typescript/createTopicWithSchema.ts +++ b/samples/typescript/createTopicWithSchema.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function createTopicWithSchema( topicNameOrId: string, schemaNameOrId: string, - encodingType: 'BINARY' | 'JSON' + encodingType: 'BINARY' | 'JSON', ) { // Get the fully qualified schema name. const schema = pubSubClient.schema(schemaNameOrId); @@ -64,13 +64,13 @@ async function createTopicWithSchema( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - encodingType: 'BINARY' | 'JSON' = 'BINARY' + encodingType: 'BINARY' | 'JSON' = 'BINARY', ) { createTopicWithSchema(topicNameOrId, schemaNameOrId, encodingType).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/typescript/createTopicWithSchemaRevisions.ts b/samples/typescript/createTopicWithSchemaRevisions.ts index 62d70d860..991f2b993 100644 --- a/samples/typescript/createTopicWithSchemaRevisions.ts +++ b/samples/typescript/createTopicWithSchemaRevisions.ts @@ -46,7 +46,7 @@ async function createTopicWithSchemaRevisions( schemaNameOrId: string, encodingType: 'BINARY' | 'JSON', firstRevisionId: string, - lastRevisionId: string + lastRevisionId: string, ) { // Get the fully qualified schema name. const schema = pubSubClient.schema(schemaNameOrId); @@ -72,14 +72,14 @@ function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', encodingType: 'BINARY' | 'JSON' = 'BINARY', firstRevisionId = 'YOUR_REVISION_ID', - lastRevisionId = 'YOUR_REVISION_ID' + lastRevisionId = 'YOUR_REVISION_ID', ) { createTopicWithSchemaRevisions( topicNameOrId, schemaNameOrId, encodingType, firstRevisionId, - lastRevisionId + lastRevisionId, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/deleteSchemaRevision.ts b/samples/typescript/deleteSchemaRevision.ts index c7d5928f0..da5868693 100644 --- a/samples/typescript/deleteSchemaRevision.ts +++ b/samples/typescript/deleteSchemaRevision.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function deleteSchemaRevision( schemaNameOrId: string, - revisionId: string + revisionId: string, ) { // Get the fully qualified schema name. const schema = pubSubClient.schema(schemaNameOrId); @@ -58,7 +58,7 @@ async function deleteSchemaRevision( function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - revisionId = 'YOUR_REVISION_ID' + revisionId = 'YOUR_REVISION_ID', ) { deleteSchemaRevision(schemaNameOrId, revisionId).catch(err => { console.error(err.message); diff --git a/samples/typescript/detachSubscription.ts b/samples/typescript/detachSubscription.ts index 6f391273d..2d2a5211f 100644 --- a/samples/typescript/detachSubscription.ts +++ b/samples/typescript/detachSubscription.ts @@ -42,7 +42,7 @@ async function detachSubscription(subscriptionNameOrId: string) { const sub = pubSubClient.subscription(subscriptionNameOrId); const [detached] = await sub.detached(); console.log( - `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}` + `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`, ); await pubSubClient.detachSubscription(subscriptionNameOrId); @@ -50,7 +50,7 @@ async function detachSubscription(subscriptionNameOrId: string) { const [updatedDetached] = await sub.detached(); console.log( - `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}` + `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`, ); } // [END pubsub_detach_subscription] diff --git a/samples/typescript/getSchemaRevision.ts b/samples/typescript/getSchemaRevision.ts index 1650cc9e2..98e366d80 100644 --- a/samples/typescript/getSchemaRevision.ts +++ b/samples/typescript/getSchemaRevision.ts @@ -49,14 +49,14 @@ async function getSchemaRevision(schemaNameOrId: string, revisionId: string) { }); console.log( - `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.` + `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.`, ); } // [END pubsub_get_schema_revision] function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - revisionId = 'YOUR_REVISION_ID' + revisionId = 'YOUR_REVISION_ID', ) { getSchemaRevision(schemaNameOrId, revisionId).catch(err => { console.error(err.message); diff --git a/samples/typescript/listSubscriptions.ts b/samples/typescript/listSubscriptions.ts index b1b1a4bde..e2bee762e 100644 --- a/samples/typescript/listSubscriptions.ts +++ b/samples/typescript/listSubscriptions.ts @@ -37,7 +37,7 @@ async function listSubscriptions() { const [subscriptions] = await pubSubClient.getSubscriptions(); console.log('Subscriptions:'); subscriptions.forEach((subscription: Subscription) => - console.log(subscription.name) + console.log(subscription.name), ); } // [END pubsub_list_subscriptions] diff --git a/samples/typescript/listTopicSubscriptions.ts b/samples/typescript/listTopicSubscriptions.ts index d21e7578f..f5c97c4ec 100644 --- a/samples/typescript/listTopicSubscriptions.ts +++ b/samples/typescript/listTopicSubscriptions.ts @@ -45,7 +45,7 @@ async function listTopicSubscriptions(topicNameOrId: string) { console.log(`Subscriptions for ${topicNameOrId}:`); subscriptions.forEach((subscription: Subscription) => - console.log(subscription.name) + console.log(subscription.name), ); } // [END pubsub_list_topic_subscriptions] diff --git a/samples/typescript/listenForAvroRecords.ts b/samples/typescript/listenForAvroRecords.ts index 665141731..94d868887 100644 --- a/samples/typescript/listenForAvroRecords.ts +++ b/samples/typescript/listenForAvroRecords.ts @@ -94,7 +94,7 @@ function listenForAvroRecords(subscriptionNameOrId: string, timeout: number) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); diff --git a/samples/typescript/listenForAvroRecordsWithRevisions.ts b/samples/typescript/listenForAvroRecordsWithRevisions.ts index cb5f4e7cf..16d7d25e7 100644 --- a/samples/typescript/listenForAvroRecordsWithRevisions.ts +++ b/samples/typescript/listenForAvroRecordsWithRevisions.ts @@ -49,7 +49,7 @@ interface ProvinceObject { async function listenForAvroRecordsWithRevisions( subscriptionNameOrId: string, - timeout: number + timeout: number, ) { // References an existing subscription const subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -105,7 +105,7 @@ async function listenForAvroRecordsWithRevisions( console.log(`\tData: ${JSON.stringify(result, null, 4)}`); console.log(`\tAttributes: ${message.attributes}`); console.log( - `\tProvince ${result?.name} is abbreviated as ${result?.post_abbr}` + `\tProvince ${result?.name} is abbreviated as ${result?.post_abbr}`, ); messageCount += 1; @@ -125,7 +125,7 @@ async function listenForAvroRecordsWithRevisions( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); @@ -133,7 +133,7 @@ function main( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/typescript/listenForErrors.ts b/samples/typescript/listenForErrors.ts index 970a64641..e48ca61ff 100644 --- a/samples/typescript/listenForErrors.ts +++ b/samples/typescript/listenForErrors.ts @@ -72,7 +72,7 @@ function listenForErrors(subscriptionNameOrId: string, timeout: number) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 10 + timeout = 10, ) { timeout = Number(timeout); listenForErrors(subscriptionNameOrId, timeout); diff --git a/samples/typescript/listenForMessages.ts b/samples/typescript/listenForMessages.ts index 582e04649..1f782c5d8 100644 --- a/samples/typescript/listenForMessages.ts +++ b/samples/typescript/listenForMessages.ts @@ -70,7 +70,7 @@ function listenForMessages(subscriptionNameOrId: string, timeout: number) { function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); listenForMessages(subscriptionNameOrId, timeout); diff --git a/samples/typescript/listenForMessagesWithExactlyOnceDelivery.ts b/samples/typescript/listenForMessagesWithExactlyOnceDelivery.ts index 9194c0b6f..cf3fde932 100644 --- a/samples/typescript/listenForMessagesWithExactlyOnceDelivery.ts +++ b/samples/typescript/listenForMessagesWithExactlyOnceDelivery.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub({ async function listenForMessagesWithExactlyOnceDelivery( subscriptionNameOrId: string, - timeout: number + timeout: number, ) { // References an existing subscription const subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -71,7 +71,7 @@ async function listenForMessagesWithExactlyOnceDelivery( // is only for permanent failures; transient errors are retried automatically. const ackError = e as AckError; console.log( - `Ack for message ${message.id} failed with error: ${ackError.errorCode}` + `Ack for message ${message.id} failed with error: ${ackError.errorCode}`, ); } }; @@ -88,11 +88,11 @@ async function listenForMessagesWithExactlyOnceDelivery( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { listenForMessagesWithExactlyOnceDelivery( subscriptionNameOrId, - Number(timeout) + Number(timeout), ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/listenForProtobufMessages.ts b/samples/typescript/listenForProtobufMessages.ts index 5a9f07290..cab7dda64 100644 --- a/samples/typescript/listenForProtobufMessages.ts +++ b/samples/typescript/listenForProtobufMessages.ts @@ -43,7 +43,7 @@ const pubSubClient = new PubSub(); async function listenForProtobufMessages( subscriptionNameOrId: string, - timeout: number + timeout: number, ) { // References an existing subscription const subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -99,7 +99,7 @@ async function listenForProtobufMessages( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); diff --git a/samples/typescript/listenWithCustomAttributes.ts b/samples/typescript/listenWithCustomAttributes.ts index 4d4455140..84921a50d 100644 --- a/samples/typescript/listenWithCustomAttributes.ts +++ b/samples/typescript/listenWithCustomAttributes.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function listenWithCustomAttributes( subscriptionNameOrId: string, - timeout: number + timeout: number, ) { // References an existing subscription, e.g. "my-subscription" const subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -50,7 +50,7 @@ async function listenWithCustomAttributes( console.log( `Received message: id ${message.id}, data ${ message.data - }, attributes: ${JSON.stringify(message.attributes)}` + }, attributes: ${JSON.stringify(message.attributes)}`, ); // "Ack" (acknowledge receipt of) the message @@ -65,9 +65,9 @@ async function listenWithCustomAttributes( } // [END pubsub_subscriber_async_pull_custom_attributes] -async function main( +function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); listenWithCustomAttributes(subscriptionNameOrId, timeout).catch(err => { diff --git a/samples/typescript/listenWithOpenTelemetryTracing.ts b/samples/typescript/listenWithOpenTelemetryTracing.ts index 198f51f8c..b501893c7 100644 --- a/samples/typescript/listenWithOpenTelemetryTracing.ts +++ b/samples/typescript/listenWithOpenTelemetryTracing.ts @@ -111,7 +111,7 @@ async function subscriptionListen(subscriptionNameOrId: string) { subscriber.removeAllListeners(); await shutdown(); r(); - }, SUBSCRIBER_TIMEOUT * 1000) + }, SUBSCRIBER_TIMEOUT * 1000), ); } // [END pubsub_subscribe_otel_tracing] diff --git a/samples/typescript/modifyPushConfig.ts b/samples/typescript/modifyPushConfig.ts index bb26dfdb1..9ad9ca51c 100644 --- a/samples/typescript/modifyPushConfig.ts +++ b/samples/typescript/modifyPushConfig.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function modifyPushConfig( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { const options: CreateSubscriptionOptions = { // Set to an HTTPS endpoint of your choice. If necessary, register @@ -58,7 +58,7 @@ async function modifyPushConfig( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { modifyPushConfig(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/typescript/optimisticSubscribe.ts b/samples/typescript/optimisticSubscribe.ts index e1fb6aafa..547d4283b 100644 --- a/samples/typescript/optimisticSubscribe.ts +++ b/samples/typescript/optimisticSubscribe.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); function optimisticSubscribe( subscriptionNameOrId: string, topicNameOrId: string, - timeout: number + timeout: number, ) { // Try using an existing subscription let subscription = pubSubClient.subscription(subscriptionNameOrId); @@ -67,7 +67,7 @@ function optimisticSubscribe( console.log('Subscription not found, creating it'); await pubSubClient.createSubscription( topicNameOrId, - subscriptionNameOrId + subscriptionNameOrId, ); // Refresh our subscriber object and re-attach the message handler. @@ -92,7 +92,7 @@ function optimisticSubscribe( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - timeout = 60 + timeout = 60, ) { timeout = Number(timeout); optimisticSubscribe(subscriptionNameOrId, topicNameOrId, timeout); diff --git a/samples/typescript/publishBatchedMessages.ts b/samples/typescript/publishBatchedMessages.ts index 4d5157beb..26a344730 100644 --- a/samples/typescript/publishBatchedMessages.ts +++ b/samples/typescript/publishBatchedMessages.ts @@ -44,7 +44,7 @@ async function publishBatchedMessages( topicNameOrId: string, data: string, maxMessages: number, - maxWaitTime: number + maxWaitTime: number, ) { // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) const dataBuffer = Buffer.from(data); @@ -66,7 +66,7 @@ async function publishBatchedMessages( data: dataBuffer, }); console.log(`Message ${messageId} published.`); - })() + })(), ); } await Promise.all(promises); @@ -77,7 +77,7 @@ function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', data = JSON.stringify({foo: 'bar'}), maxMessages = 10, - maxWaitTime = 10 + maxWaitTime = 10, ) { maxMessages = Number(maxMessages); maxWaitTime = Number(maxWaitTime); @@ -85,7 +85,7 @@ function main( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/typescript/publishMessage.ts b/samples/typescript/publishMessage.ts index eb7526143..0035cbee9 100644 --- a/samples/typescript/publishMessage.ts +++ b/samples/typescript/publishMessage.ts @@ -51,7 +51,7 @@ async function publishMessage(topicNameOrId: string, data: string) { console.log(`Message ${messageId} published.`); } catch (error) { console.error( - `Received error while publishing: ${(error as Error).message}` + `Received error while publishing: ${(error as Error).message}`, ); process.exitCode = 1; } @@ -61,7 +61,7 @@ async function publishMessage(topicNameOrId: string, data: string) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) + data = JSON.stringify({foo: 'bar'}), ) { publishMessage(topicNameOrId, data).catch(err => { console.error(err.message); diff --git a/samples/typescript/publishMessageWithCustomAttributes.ts b/samples/typescript/publishMessageWithCustomAttributes.ts index df285cb29..158fef8d2 100644 --- a/samples/typescript/publishMessageWithCustomAttributes.ts +++ b/samples/typescript/publishMessageWithCustomAttributes.ts @@ -44,7 +44,7 @@ interface Attributes { async function publishMessageWithCustomAttributes( topicNameOrId: string, - data: string + data: string, ) { // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) const dataBuffer = Buffer.from(data); @@ -68,7 +68,7 @@ async function publishMessageWithCustomAttributes( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) + data = JSON.stringify({foo: 'bar'}), ) { publishMessageWithCustomAttributes(topicNameOrId, data).catch(console.error); } diff --git a/samples/typescript/publishOrderedMessage.ts b/samples/typescript/publishOrderedMessage.ts index 0fb083208..3f2ebfe15 100644 --- a/samples/typescript/publishOrderedMessage.ts +++ b/samples/typescript/publishOrderedMessage.ts @@ -49,7 +49,7 @@ const pubSubClient = new PubSub({ async function publishOrderedMessage( topicNameOrId: string, data: string, - orderingKey: string + orderingKey: string, ) { // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) const dataBuffer = Buffer.from(data); @@ -80,12 +80,12 @@ async function publishOrderedMessage( } // [END pubsub_publish_with_ordering_keys] -async function main( +function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', data = JSON.stringify({foo: 'bar'}), - orderingKey = 'key1' + orderingKey = 'key1', ) { - await publishOrderedMessage(topicNameOrId, data, orderingKey).catch(err => { + publishOrderedMessage(topicNameOrId, data, orderingKey).catch(err => { console.error(err.message); process.exitCode = 1; }); diff --git a/samples/typescript/publishWithRetrySettings.ts b/samples/typescript/publishWithRetrySettings.ts index b47498275..86084b3ab 100644 --- a/samples/typescript/publishWithRetrySettings.ts +++ b/samples/typescript/publishWithRetrySettings.ts @@ -98,7 +98,7 @@ async function publishWithRetrySettings(topicNameOrId: string, data: string) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) + data = JSON.stringify({foo: 'bar'}), ) { publishWithRetrySettings(topicNameOrId, data).catch(err => { console.error(err.message); diff --git a/samples/typescript/quickstart.ts b/samples/typescript/quickstart.ts index c402f0a35..a696668ed 100644 --- a/samples/typescript/quickstart.ts +++ b/samples/typescript/quickstart.ts @@ -26,7 +26,7 @@ import {PubSub} from '@google-cloud/pubsub'; async function quickstart( projectId = 'your-project-id', // Your Google Cloud Platform project ID topicNameOrId = 'my-topic', // Name for the new topic to create - subscriptionName = 'my-sub' // Name for the new subscription to create + subscriptionName = 'my-sub', // Name for the new subscription to create ) { // Instantiates a client const pubsub = new PubSub({projectId}); @@ -51,12 +51,11 @@ async function quickstart( }); // Send a message to the topic - topic.publishMessage({data: Buffer.from('Test message!')}); + await topic.publishMessage({data: Buffer.from('Test message!')}); } // [END pubsub_quickstart_create_topic] -process.on('unhandledRejection', err => { - console.error((err as Error).message); +quickstart(...process.argv.slice(2)).catch(err => { + console.error(err.message); process.exitCode = 1; }); -quickstart(...process.argv.slice(2)); diff --git a/samples/typescript/removeDeadLetterPolicy.ts b/samples/typescript/removeDeadLetterPolicy.ts index b7c11401b..c0e031c36 100644 --- a/samples/typescript/removeDeadLetterPolicy.ts +++ b/samples/typescript/removeDeadLetterPolicy.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function removeDeadLetterPolicy( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { const metadata: SubscriptionMetadata = { deadLetterPolicy: null, @@ -52,14 +52,14 @@ async function removeDeadLetterPolicy( .setMetadata(metadata); console.log( - `Removed dead letter topic from ${subscriptionNameOrId} subscription.` + `Removed dead letter topic from ${subscriptionNameOrId} subscription.`, ); } // [END pubsub_dead_letter_remove] function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/typescript/resumePublish.ts b/samples/typescript/resumePublish.ts index 2a7f9680f..1d8af5d04 100644 --- a/samples/typescript/resumePublish.ts +++ b/samples/typescript/resumePublish.ts @@ -43,7 +43,7 @@ const pubSubClient = new PubSub(); async function resumePublish( topicNameOrId: string, data: string, - orderingKey: string + orderingKey: string, ) { // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) const dataBuffer = Buffer.from(data); @@ -80,7 +80,7 @@ async function resumePublish( async function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', data = JSON.stringify({foo: 'bar'}), - orderingKey = 'key1' + orderingKey = 'key1', ) { return await resumePublish(topicNameOrId, data, orderingKey).catch(err => { console.error(err.message); diff --git a/samples/typescript/rollbackSchema.ts b/samples/typescript/rollbackSchema.ts index d2e1ac30f..98601e07a 100644 --- a/samples/typescript/rollbackSchema.ts +++ b/samples/typescript/rollbackSchema.ts @@ -56,7 +56,7 @@ async function rollbackSchema(schemaNameOrId: string, revisionId: string) { function main( schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID', - revisionId = 'YOUR_REVISION_ID' + revisionId = 'YOUR_REVISION_ID', ) { rollbackSchema(schemaNameOrId, revisionId).catch(err => { console.error(err.message); diff --git a/samples/typescript/subscribeWithFlowControlSettings.ts b/samples/typescript/subscribeWithFlowControlSettings.ts index d9be8dd66..1fc93eaed 100644 --- a/samples/typescript/subscribeWithFlowControlSettings.ts +++ b/samples/typescript/subscribeWithFlowControlSettings.ts @@ -44,7 +44,7 @@ const pubSubClient = new PubSub(); async function subscribeWithFlowControlSettings( subscriptionNameOrId: string, maxInProgress: number, - timeout: number + timeout: number, ) { const subscriberOptions: SubscriberOptions = { flowControl: { @@ -56,11 +56,11 @@ async function subscribeWithFlowControlSettings( // Note that flow control settings are not persistent across subscribers. const subscription = pubSubClient.subscription( subscriptionNameOrId, - subscriberOptions + subscriberOptions, ); console.log( - `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.` + `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.`, ); const messageHandler = (message: Message) => { @@ -75,8 +75,8 @@ async function subscribeWithFlowControlSettings( subscription.on('message', messageHandler); // Wait a while for the subscription to run. (Part of the sample only.) - setTimeout(() => { - subscription.close(); + setTimeout(async () => { + await subscription.close(); }, timeout * 1000); } // [END pubsub_subscriber_flow_settings] @@ -84,7 +84,7 @@ async function subscribeWithFlowControlSettings( function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', maxInProgress = 1, - timeout = 10 + timeout = 10, ) { maxInProgress = Number(maxInProgress); timeout = Number(timeout); @@ -92,7 +92,7 @@ function main( subscribeWithFlowControlSettings( subscriptionNameOrId, maxInProgress, - timeout + timeout, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/synchronousPull.ts b/samples/typescript/synchronousPull.ts index 0f6d5807e..7d68d1672 100644 --- a/samples/typescript/synchronousPull.ts +++ b/samples/typescript/synchronousPull.ts @@ -41,7 +41,7 @@ const subClient = new v1.SubscriberClient(); async function synchronousPull( projectId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { // The low level API client requires a name only. const formattedSubscription = @@ -85,7 +85,7 @@ async function synchronousPull( function main( projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { synchronousPull(projectId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/typescript/synchronousPullWithDeliveryAttempts.ts b/samples/typescript/synchronousPullWithDeliveryAttempts.ts index 0cf650e6c..fd2048cde 100644 --- a/samples/typescript/synchronousPullWithDeliveryAttempts.ts +++ b/samples/typescript/synchronousPullWithDeliveryAttempts.ts @@ -41,7 +41,7 @@ const subClient = new v1.SubscriberClient(); async function synchronousPullWithDeliveryAttempts( projectId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { // The low level API client requires a name only. const formattedSubscription = @@ -83,13 +83,13 @@ async function synchronousPullWithDeliveryAttempts( function main( projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { synchronousPullWithDeliveryAttempts(projectId, subscriptionNameOrId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/typescript/updateDeadLetterPolicy.ts b/samples/typescript/updateDeadLetterPolicy.ts index 18ba8501f..dc26d1d67 100644 --- a/samples/typescript/updateDeadLetterPolicy.ts +++ b/samples/typescript/updateDeadLetterPolicy.ts @@ -40,7 +40,7 @@ const pubSubClient = new PubSub(); async function updateDeadLetterPolicy( topicNameOrId: string, - subscriptionNameOrId: string + subscriptionNameOrId: string, ) { const metadata: SubscriptionMetadata = { deadLetterPolicy: { @@ -60,7 +60,7 @@ async function updateDeadLetterPolicy( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/typescript/updateTopicIngestionType.ts b/samples/typescript/updateTopicIngestionType.ts index 10b4f733f..be0919aeb 100644 --- a/samples/typescript/updateTopicIngestionType.ts +++ b/samples/typescript/updateTopicIngestionType.ts @@ -46,7 +46,7 @@ async function updateTopicIngestionType( awsRoleArn: string, gcpServiceAccount: string, streamArn: string, - consumerArn: string + consumerArn: string, ) { const metadata: TopicMetadata = { ingestionDataSourceSettings: { @@ -70,14 +70,14 @@ function main( roleArn = 'arn:aws:iam:...', gcpServiceAccount = 'ingestion-account@...', streamArn = 'arn:aws:kinesis:...', - consumerArn = 'arn:aws:kinesis:...' + consumerArn = 'arn:aws:kinesis:...', ) { updateTopicIngestionType( topicNameOrId, roleArn, gcpServiceAccount, streamArn, - consumerArn + consumerArn, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/typescript/updateTopicSchema.ts b/samples/typescript/updateTopicSchema.ts index c31bad802..38fa93407 100644 --- a/samples/typescript/updateTopicSchema.ts +++ b/samples/typescript/updateTopicSchema.ts @@ -42,7 +42,7 @@ const pubSubClient = new PubSub(); async function updateTopicSchema( topicNameOrId: string, firstRevisionId: string, - lastRevisionId: string + lastRevisionId: string, ) { const metadata: TopicMetadata = { schemaSettings: { @@ -60,13 +60,13 @@ async function updateTopicSchema( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', firstRevisionId = 'YOUR_REVISION_ID', - lastRevisionId = 'YOUR_REVISION_ID' + lastRevisionId = 'YOUR_REVISION_ID', ) { updateTopicSchema(topicNameOrId, firstRevisionId, lastRevisionId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/samples/updateDeadLetterPolicy.js b/samples/updateDeadLetterPolicy.js index b3d782d00..ba379f6dc 100644 --- a/samples/updateDeadLetterPolicy.js +++ b/samples/updateDeadLetterPolicy.js @@ -61,7 +61,7 @@ async function updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId) { function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', ) { updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { console.error(err.message); diff --git a/samples/updateTopicIngestionType.js b/samples/updateTopicIngestionType.js index 16a5baf30..d5bba5208 100644 --- a/samples/updateTopicIngestionType.js +++ b/samples/updateTopicIngestionType.js @@ -50,7 +50,7 @@ async function updateTopicIngestionType( awsRoleArn, gcpServiceAccount, streamArn, - consumerArn + consumerArn, ) { const metadata = { ingestionDataSourceSettings: { @@ -74,14 +74,14 @@ function main( roleArn = 'arn:aws:iam:...', gcpServiceAccount = 'ingestion-account@...', streamArn = 'arn:aws:kinesis:...', - consumerArn = 'arn:aws:kinesis:...' + consumerArn = 'arn:aws:kinesis:...', ) { updateTopicIngestionType( topicNameOrId, roleArn, gcpServiceAccount, streamArn, - consumerArn + consumerArn, ).catch(err => { console.error(err.message); process.exitCode = 1; diff --git a/samples/updateTopicSchema.js b/samples/updateTopicSchema.js index 5de59bcd9..e36c0233a 100644 --- a/samples/updateTopicSchema.js +++ b/samples/updateTopicSchema.js @@ -46,7 +46,7 @@ const pubSubClient = new PubSub(); async function updateTopicSchema( topicNameOrId, firstRevisionId, - lastRevisionId + lastRevisionId, ) { const metadata = { schemaSettings: { @@ -64,13 +64,13 @@ async function updateTopicSchema( function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', firstRevisionId = 'YOUR_REVISION_ID', - lastRevisionId = 'YOUR_REVISION_ID' + lastRevisionId = 'YOUR_REVISION_ID', ) { updateTopicSchema(topicNameOrId, firstRevisionId, lastRevisionId).catch( err => { console.error(err.message); process.exitCode = 1; - } + }, ); } diff --git a/src/debug.ts b/src/debug.ts index b7856dd44..532b6d2fe 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -31,6 +31,6 @@ export class DebugMessage { constructor( public message: string, - public error?: Error + public error?: Error, ) {} } diff --git a/src/default-options.ts b/src/default-options.ts index 4e502e8bd..7f09392d5 100644 --- a/src/default-options.ts +++ b/src/default-options.ts @@ -34,16 +34,16 @@ export const defaultOptions = { // The maximum length of time a message's lease will be extended by. maxAckDeadline: Duration.from({minutes: 10}), - // The maximum number of minutes that a message's lease will ever + // The maximum amount of time that a message's lease will ever // be extended. - maxExtensionMinutes: 60, + maxExtensionTime: Duration.from({minutes: 60}), // The maximum number of subscription streams/threads that will ever // be opened. maxStreams: 5, // The starting number of seconds that ack deadlines will be extended. - ackDeadline: 10, + startingAckDeadline: Duration.from({seconds: 10}), }, publish: { diff --git a/src/exponential-retry.ts b/src/exponential-retry.ts index ddd3a4cdc..dd12a5b0b 100644 --- a/src/exponential-retry.ts +++ b/src/exponential-retry.ts @@ -170,7 +170,7 @@ export class ExponentialRetry { next.retryInfo!.callback( next as unknown as T, - Duration.from({millis: now - next.retryInfo!.firstRetry}) + Duration.from({millis: now - next.retryInfo!.firstRetry}), ); } else { break; diff --git a/src/histogram.ts b/src/histogram.ts index 6a7d50c2b..0b00223ee 100644 --- a/src/histogram.ts +++ b/src/histogram.ts @@ -34,7 +34,7 @@ export class Histogram { constructor(options?: HistogramOptions) { this.options = Object.assign( {min: 0, max: Number.MAX_SAFE_INTEGER}, - options + options, ); this.data = new Map(); this.length = 0; diff --git a/src/iam.ts b/src/iam.ts index efc775013..eec8932e9 100644 --- a/src/iam.ts +++ b/src/iam.ts @@ -168,7 +168,7 @@ export class IAM { getPolicy(gaxOpts: CallOptions, callback: GetPolicyCallback): void; getPolicy( optsOrCallback?: CallOptions | GetPolicyCallback, - callback?: GetPolicyCallback + callback?: GetPolicyCallback, ): Promise | void { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -184,7 +184,7 @@ export class IAM { reqOpts, gaxOpts, }, - callback! + callback!, ); } @@ -251,13 +251,13 @@ export class IAM { setPolicy( policy: Policy, gaxOpts: CallOptions, - callback: SetPolicyCallback + callback: SetPolicyCallback, ): void; setPolicy(policy: Policy, callback: SetPolicyCallback): void; setPolicy( policy: Policy, optsOrCallback?: CallOptions | SetPolicyCallback, - callback?: SetPolicyCallback + callback?: SetPolicyCallback, ): Promise | void { if (!(typeof policy === 'object')) { throw new Error('A policy object is required.'); @@ -278,7 +278,7 @@ export class IAM { reqOpts, gaxOpts, }, - callback! + callback!, ); } @@ -362,21 +362,21 @@ export class IAM { */ testPermissions( permissions: string | string[], - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; testPermissions( permissions: string | string[], gaxOpts: CallOptions, - callback: TestIamPermissionsCallback + callback: TestIamPermissionsCallback, ): void; testPermissions( permissions: string | string[], - callback: TestIamPermissionsCallback + callback: TestIamPermissionsCallback, ): void; testPermissions( permissions: string | string[], optsOrCallback?: CallOptions | TestIamPermissionsCallback, - callback?: TestIamPermissionsCallback + callback?: TestIamPermissionsCallback, ): Promise | void { if (!Array.isArray(permissions) && !(typeof permissions === 'string')) { throw new Error('Permissions are required.'); @@ -411,10 +411,10 @@ export class IAM { acc[permission] = availablePermissions.indexOf(permission) > -1; return acc; }, - {} as {[key: string]: boolean} + {} as {[key: string]: boolean}, ); callback!(null, permissionHash, resp!); - } + }, ); } } diff --git a/src/index.ts b/src/index.ts index 15b5a1d32..2c9371069 100644 --- a/src/index.ts +++ b/src/index.ts @@ -184,8 +184,3 @@ if (process.env.DEBUG_GRPC) { } import * as protos from '../protos/protos'; export {protos}; - -// Deprecated; please see the updated OpenTelemetry sample -// for an example of how to use telemetry in this library. -import {legacyExports} from './telemetry-tracing'; -export {legacyExports as openTelemetry}; diff --git a/src/lease-manager.ts b/src/lease-manager.ts index 88e92640a..cb55af2fe 100644 --- a/src/lease-manager.ts +++ b/src/lease-manager.ts @@ -23,10 +23,6 @@ export interface FlowControlOptions { allowExcessMessages?: boolean; maxBytes?: number; maxMessages?: number; - maxExtensionMinutes?: number; - - /** @deprecated Use maxExtensionMinutes. */ - maxExtension?: number; } /** @@ -194,28 +190,9 @@ export class LeaseManager extends EventEmitter { * @private */ setOptions(options: FlowControlOptions): void { - // Convert the old deprecated maxExtension to avoid breaking clients, - // but allow only one. - if ( - options.maxExtension !== undefined && - options.maxExtensionMinutes !== undefined - ) { - throw new RangeError( - 'Only one of "maxExtension" or "maxExtensionMinutes" may be set for subscriber lease management options' - ); - } - if ( - options.maxExtension !== undefined && - options.maxExtensionMinutes === undefined - ) { - options.maxExtensionMinutes = options.maxExtension / 60; - delete options.maxExtension; - } - const defaults: FlowControlOptions = { allowExcessMessages: true, maxBytes: defaultOptions.subscription.maxOutstandingBytes, - maxExtensionMinutes: defaultOptions.subscription.maxExtensionMinutes, maxMessages: defaultOptions.subscription.maxOutstandingMessages, }; @@ -260,19 +237,20 @@ export class LeaseManager extends EventEmitter { * @private */ private _extendDeadlines(): void { - const deadline = this._subscriber.ackDeadline; + const deadline = Duration.from({seconds: this._subscriber.ackDeadline}); + const maxExtensionMinutes = + this._subscriber.maxExtensionTime.totalOf('minute'); for (const message of this._messages) { // Lifespan here is in minutes. const lifespan = (Date.now() - message.received) / (60 * 1000); - if (lifespan < this._options.maxExtensionMinutes!) { - const deadlineDuration = Duration.from({seconds: deadline}); - message.subSpans.modAckStart(deadlineDuration, false); + if (lifespan < maxExtensionMinutes) { + message.subSpans.modAckStart(deadline, false); if (this._subscriber.isExactlyOnceDelivery) { message - .modAckWithResponse(deadline) + .modAckWithResponse(deadline.totalOf('second')) .catch(e => { // In the case of a permanent failure (temporary failures are retried), // we need to stop trying to lease-manage the message. @@ -283,8 +261,8 @@ export class LeaseManager extends EventEmitter { message.subSpans.modAckEnd(); }); } else { - message.modAck(deadline); - message.subSpans.modAckStart(deadlineDuration, false); + message.modAck(deadline.totalOf('second')); + message.subSpans.modAckStart(deadline, false); } } else { this.remove(message); diff --git a/src/message-queues.ts b/src/message-queues.ts index adc565c3e..1788991cf 100644 --- a/src/message-queues.ts +++ b/src/message-queues.ts @@ -89,7 +89,7 @@ export class BatchError extends DebugMessage { `Failed to "${rpc}" for ${ackIds.length} message(s). Reason: ${ process.env.DEBUG_GRPC ? err.stack : err.message }`, - err + err, ); this.ackIds = ackIds; @@ -141,7 +141,7 @@ export abstract class MessageQueue { this._subscriber = sub; this._retrier = new ExponentialRetry( Duration.from({seconds: 1}), - Duration.from({seconds: 64}) + Duration.from({seconds: 64}), ); this.setOptions(options); @@ -167,7 +167,7 @@ export abstract class MessageQueue { if (r.responsePromise) { if (isExactlyOnceDelivery) { r.responsePromise.reject( - new AckError(AckResponses.Invalid, 'Subscriber closed') + new AckError(AckResponses.Invalid, 'Subscriber closed'), ); } else { r.responsePromise.resolve(); @@ -195,12 +195,12 @@ export abstract class MessageQueue { * @param {number} [deadline] The deadline in seconds. * @private */ - add(message: Message, deadline?: number): Promise { + async add(message: Message, deadline?: number): Promise { if (this._closed) { if (this._subscriber.isExactlyOnceDelivery) { throw new AckError(AckResponses.Invalid, 'Subscriber closed'); } else { - return Promise.resolve(); + return; } } @@ -213,7 +213,7 @@ export abstract class MessageQueue { this._requests.length + 1 >= maxMessages! || this.bytes + size >= MAX_BATCH_BYTES ) { - this.flush(); + await this.flush(); } // Add the message to the current batch. @@ -249,7 +249,7 @@ export abstract class MessageQueue { // Has it been too long? if (totalTime.totalOf('minute') >= 10 || this.shouldFailEarly(message)) { message.responsePromise?.reject( - new AckError(AckResponses.Invalid, 'Retried for too long') + new AckError(AckResponses.Invalid, 'Retried for too long'), ); return; } @@ -264,7 +264,7 @@ export abstract class MessageQueue { if (!this._timer) { this._timer = setTimeout( () => this.flush(), - this._options.maxMilliseconds! + this._options.maxMilliseconds!, ); } } @@ -396,7 +396,7 @@ export abstract class MessageQueue { handleAckFailures( operation: string, batch: QueuedMessages, - rpcError: GoogleError + rpcError: GoogleError, ) { const toSucceed: QueuedMessages = []; const toRetry: QueuedMessages = []; @@ -505,7 +505,7 @@ export class AckQueue extends MessageQueue { const responseSpan = tracing.PubsubSpans.createAckRpcSpan( batch.map(b => b.message.tracingSpan), this._subscriber.name, - 'AckQueue._sendBatch' + 'AckQueue._sendBatch', ); const client = await this._subscriber.getClient(); const ackIds = batch.map(({message}) => message.ackId); @@ -576,7 +576,7 @@ export class ModAckQueue extends MessageQueue { table[message.deadline!].push(message); return table; }, - {} + {}, ); const callOptions = this.getCallOptions(); @@ -591,7 +591,7 @@ export class ModAckQueue extends MessageQueue { this._subscriber.name, ackDeadlineSeconds === 0 ? 'nack' : 'modack', 'ModAckQueue._sendBatch', - Duration.from({seconds: ackDeadlineSeconds}) + Duration.from({seconds: ackDeadlineSeconds}), ); try { @@ -617,7 +617,7 @@ export class ModAckQueue extends MessageQueue { const newBatch = this.handleAckFailures( 'modAck', messages, - grpcError + grpcError, ); return newBatch.toRetry; } diff --git a/src/message-stream.ts b/src/message-stream.ts index 073658382..0706d3b22 100644 --- a/src/message-stream.ts +++ b/src/message-stream.ts @@ -114,7 +114,7 @@ export class ChannelError extends Error implements grpc.ServiceError { super( `Failed to connect to channel. Reason: ${ process.env.DEBUG_GRPC ? err.stack : err.message - }` + }`, ); this.code = err.message.includes('deadline') ? grpc.status.DEADLINE_EXCEEDED @@ -156,7 +156,7 @@ export class MessageStream extends PassThrough { this._options = options; this._retrier = new ExponentialRetry<{}>( options.retryMinBackoff!, // Filled by DEFAULT_OPTIONS - options.retryMaxBackoff! + options.retryMaxBackoff!, ); this._streams = []; @@ -178,7 +178,7 @@ export class MessageStream extends PassThrough { this._keepAliveHandle = setInterval( () => this._keepAlive(), - KEEP_ALIVE_INTERVAL + KEEP_ALIVE_INTERVAL, ); this._keepAliveHandle.unref(); } @@ -346,7 +346,7 @@ export class MessageStream extends PassThrough { */ private async _getClient(): Promise { const client = await this._subscriber.getClient(); - client.initialize(); + await client.initialize(); return client.subscriberStub as Promise; } @@ -391,22 +391,22 @@ export class MessageStream extends PassThrough { 'debug', new DebugMessage( `Subscriber stream ${index} has ended with status ${status.code}; will be retried.`, - statusError - ) + statusError, + ), ); if (PullRetry.resetFailures(status)) { this._retrier.reset(this._streams[index]); } - this._retrier.retryLater(this._streams[index], () => { - this._fillOne(index); - }); + this._retrier.retryLater(this._streams[index], () => + this._fillOne(index), + ); } else if (this._activeStreams() === 0) { this.emit( 'debug', new DebugMessage( `Subscriber stream ${index} has ended with status ${status.code}; will not be retried.`, - statusError - ) + statusError, + ), ); // No streams left, and nothing to retry. diff --git a/src/publisher/flow-control.ts b/src/publisher/flow-control.ts index ee467e329..6683c9e5e 100644 --- a/src/publisher/flow-control.ts +++ b/src/publisher/flow-control.ts @@ -73,7 +73,7 @@ export class FlowControl { ) { // Undefined is okay, but if either is zero, no publishes ever happen. throw new Error( - 'When using publisher flow control, maxOutstandingBytes and maxOutstandingMessages must not be zero' + 'When using publisher flow control, maxOutstandingBytes and maxOutstandingMessages must not be zero', ); } } diff --git a/src/publisher/flow-publisher.ts b/src/publisher/flow-publisher.ts index 74e3b3279..34e1a8dd0 100644 --- a/src/publisher/flow-publisher.ts +++ b/src/publisher/flow-publisher.ts @@ -90,7 +90,7 @@ export class FlowControlledPublisher { const waitPromise = this.flowControl.willSend(size, 1); return waitPromise.then(doPublish); } else { - this.flowControl.willSend(size, 1).then(() => {}); + void this.flowControl.willSend(size, 1).then(() => {}); doPublish(); return null; } diff --git a/src/publisher/index.ts b/src/publisher/index.ts index 01692a5a1..2046c6169 100644 --- a/src/publisher/index.ts +++ b/src/publisher/index.ts @@ -38,9 +38,6 @@ export interface PublishOptions { flowControlOptions?: FlowControlOptions; gaxOpts?: CallOptions; messageOrdering?: boolean; - - /** @deprecated Unset and use context propagation. */ - enableOpenTelemetryTracing?: boolean; } /** @@ -87,7 +84,7 @@ export class Publisher { constructor(topic: Topic, options?: PublishOptions) { this.flowControl = new FlowControl( - options?.flowControlOptions || flowControlDefaults + options?.flowControlOptions || flowControlDefaults, ); this.setOptions(options); this.topic = topic; @@ -124,8 +121,8 @@ export class Publisher { q.removeListener('drain', flushResolver); }; q.on('drain', flushResolver); - }) - ) + }), + ), ); const allPublishes = Promise.all(toDrain.map(q => q.publishDrain())); @@ -157,12 +154,12 @@ export class Publisher { publish( data: Buffer, attributes: Attributes, - callback: PublishCallback + callback: PublishCallback, ): void; publish( data: Buffer, attrsOrCb?: Attributes | PublishCallback, - callback?: PublishCallback + callback?: PublishCallback, ): Promise | void { const attributes = typeof attrsOrCb === 'object' ? attrsOrCb : {}; callback = typeof attrsOrCb === 'function' ? attrsOrCb : callback; @@ -184,7 +181,7 @@ export class Publisher { publishMessage(message: PubsubMessage, callback: PublishCallback): void; publishMessage( message: PubsubMessage, - callback?: PublishCallback + callback?: PublishCallback, ): Promise | void { const {data, attributes = {}} = message; @@ -193,14 +190,14 @@ export class Publisher { // - `attributes` that are not empty if (data && !(data instanceof Uint8Array)) { throw new TypeError( - 'Data must be in the form of a Buffer or Uint8Array.' + 'Data must be in the form of a Buffer or Uint8Array.', ); } const keys = Object.keys(attributes!); if (!data && keys.length === 0) { throw new TypeError( - 'If data is undefined, at least one attribute must be present.' + 'If data is undefined, at least one attribute must be present.', ); } @@ -270,10 +267,9 @@ export class Publisher { gaxOpts: { isBundling: false, }, - enableOpenTelemetryTracing: false, flowControlOptions: Object.assign( {}, - flowControlDefaults + flowControlDefaults, ) as FlowControlOptions, }; @@ -290,26 +286,23 @@ export class Publisher { setOptions(options = {} as PublishOptions): void { const defaults = this.getOptionDefaults(); - const { - batching, - gaxOpts, - messageOrdering, - enableOpenTelemetryTracing, - flowControlOptions, - } = extend(true, defaults, options); + const {batching, gaxOpts, messageOrdering, flowControlOptions} = extend( + true, + defaults, + options, + ); this.settings = { batching: { maxBytes: Math.min(batching!.maxBytes!, BATCH_LIMITS.maxBytes!), maxMessages: Math.min( batching!.maxMessages!, - BATCH_LIMITS.maxMessages! + BATCH_LIMITS.maxMessages!, ), maxMilliseconds: batching!.maxMilliseconds, }, gaxOpts, messageOrdering, - enableOpenTelemetryTracing, flowControlOptions, }; @@ -336,7 +329,7 @@ export class Publisher { * @param {PubsubMessage} message The message to create a span for */ getParentSpan(message: PubsubMessage, caller: string): Span | undefined { - const enabled = tracing.isEnabled(this.settings); + const enabled = tracing.isEnabled(); if (!enabled) { return undefined; } @@ -348,12 +341,12 @@ export class Publisher { const span = tracing.PubsubSpans.createPublisherSpan( message, this.topic.name, - caller + caller, ); // If the span's context is valid we should inject the propagation trace context. if (span && isSpanContextValid(span.spanContext())) { - tracing.injectSpan(span, message, enabled); + tracing.injectSpan(span, message); } return span; diff --git a/src/publisher/message-batch.ts b/src/publisher/message-batch.ts index a1ecdb0bf..96e091bc3 100644 --- a/src/publisher/message-batch.ts +++ b/src/publisher/message-batch.ts @@ -59,7 +59,7 @@ export class MessageBatch { constructor( public options: BatchPublishOptions, - public topicName: string + public topicName: string, ) { this.messages = []; this.callbacks = []; @@ -90,6 +90,12 @@ export class MessageBatch { tracing.PubsubSpans.createPublishSchedulerSpan(message); } + /** + * Ends the current batch, and returns the messages and callbacks we've queued up. + * + * @private + * @internal + */ end(): BatchResults { this.messages.forEach(m => m.publishSchedulerSpan?.end()); return { diff --git a/src/publisher/message-queues.ts b/src/publisher/message-queues.ts index 8ed396bc8..23f9ab8fb 100644 --- a/src/publisher/message-queues.ts +++ b/src/publisher/message-queues.ts @@ -90,7 +90,7 @@ export abstract class MessageQueue extends EventEmitter { */ async _publish( messages: PubsubMessage[], - callbacks: PublishCallback[] + callbacks: PublishCallback[], ): Promise { const {topic, settings} = this.publisher; const reqOpts = { @@ -118,7 +118,7 @@ export abstract class MessageQueue extends EventEmitter { const rpcSpan = tracing.PubsubSpans.createPublishRpcSpan( spanMessages, topic.name, - 'MessageQueue._publish' + 'MessageQueue._publish', ); const requestCallback = topic.request; diff --git a/src/publisher/pubsub-message.ts b/src/publisher/pubsub-message.ts index ac69563b1..ac9799416 100644 --- a/src/publisher/pubsub-message.ts +++ b/src/publisher/pubsub-message.ts @@ -87,7 +87,7 @@ export interface PubsubMessage * @internal */ export function filterMessage( - message: PubsubMessage + message: PubsubMessage, ): google.pubsub.v1.IPubsubMessage { const filtered = {} as PubsubMessage; if (message.data) { @@ -126,7 +126,7 @@ export function filterMessage( * @internal */ export function calculateMessageSize( - message: PubsubMessage | google.pubsub.v1.IPubsubMessage + message: PubsubMessage | google.pubsub.v1.IPubsubMessage, ) { // If it's not a PubsubMessage, we'll augment it into one. const msg = message as unknown as PubsubMessage; diff --git a/src/pubsub.ts b/src/pubsub.ts index cbf0548c5..075d673f5 100644 --- a/src/pubsub.ts +++ b/src/pubsub.ts @@ -167,7 +167,7 @@ export interface ResourceCallback { ( err: gax.grpc.ServiceError | null, resource?: Resource | null, - response?: Response | null + response?: Response | null, ): void; } @@ -184,7 +184,7 @@ export interface PagedCallback { err: gax.grpc.ServiceError | null, results?: Item[] | null, nextQuery?: {} | null, - response?: Response | null + response?: Response | null, ): void; } @@ -200,7 +200,7 @@ export type ObjectStream = { prependListener(event: 'data', listener: (data: O) => void): ObjectStream; prependOnceListener( event: 'data', - listener: (data: O) => void + listener: (data: O) => void, ): ObjectStream; } & Transform; @@ -281,13 +281,13 @@ export class PubSub { // tslint:disable-next-line variable-name Promise?: PromiseConstructor; getSubscriptionsStream = paginator.streamify( - 'getSubscriptions' + 'getSubscriptions', ) as () => ObjectStream; getSnapshotsStream = paginator.streamify( - 'getSnapshots' + 'getSnapshots', ) as () => ObjectStream; getTopicsStream = paginator.streamify( - 'getTopics' + 'getTopics', ) as () => ObjectStream; isOpen = true; @@ -321,7 +321,7 @@ export class PubSub { libVersion: PKG.version, scopes: Object.keys(allScopes), }, - options + options, ); if (this.options.enableOpenTelemetryTracing) { @@ -412,7 +412,7 @@ export class PubSub { schemaId: string, type: SchemaType, definition: string, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise { // This populates projectId for us. await this.getClientConfig(); @@ -520,24 +520,24 @@ export class PubSub { createSubscription( topic: Topic | string, name: string, - options?: CreateSubscriptionOptions + options?: CreateSubscriptionOptions, ): Promise; createSubscription( topic: Topic | string, name: string, - callback: CreateSubscriptionCallback + callback: CreateSubscriptionCallback, ): void; createSubscription( topic: Topic | string, name: string, options: CreateSubscriptionOptions, - callback: CreateSubscriptionCallback + callback: CreateSubscriptionCallback, ): void; createSubscription( topic: Topic | string, name: string, optionsOrCallback?: CreateSubscriptionOptions | CreateSubscriptionCallback, - callback?: CreateSubscriptionCallback + callback?: CreateSubscriptionCallback, ): Promise | void { if (typeof topic !== 'string' && !(topic instanceof Topic)) { throw new Error('A Topic is required for a new subscription.'); @@ -564,7 +564,7 @@ export class PubSub { delete options.flowControl; const metadata = Subscription.formatMetadata_( - options as SubscriptionMetadata + options as SubscriptionMetadata, ); let subscriptionCtorOptions = flowControl ? {flowControl} : {}; @@ -591,7 +591,7 @@ export class PubSub { subscription.metadata = resp!; callback!(null, subscription, resp!); - } + }, ); } @@ -639,21 +639,21 @@ export class PubSub { */ createTopic( name: string | TopicMetadata, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; createTopic( name: string | TopicMetadata, - callback: CreateTopicCallback + callback: CreateTopicCallback, ): void; createTopic( name: string | TopicMetadata, gaxOpts: CallOptions, - callback: CreateTopicCallback + callback: CreateTopicCallback, ): void; createTopic( name: string | TopicMetadata, optsOrCallback?: CallOptions | CreateTopicCallback, - callback?: CreateTopicCallback + callback?: CreateTopicCallback, ): Promise | void { const reqOpts: TopicMetadata = typeof name === 'string' @@ -686,7 +686,7 @@ export class PubSub { topic.metadata = resp!; callback!(null, topic, resp!); - } + }, ); } @@ -722,18 +722,18 @@ export class PubSub { */ detachSubscription( name: string, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; detachSubscription(name: string, callback: DetachSubscriptionCallback): void; detachSubscription( name: string, gaxOpts: CallOptions, - callback: DetachSubscriptionCallback + callback: DetachSubscriptionCallback, ): void; detachSubscription( name: string, optsOrCallback?: CallOptions | DetachSubscriptionCallback, - callback?: DetachSubscriptionCallback + callback?: DetachSubscriptionCallback, ): Promise | void { if (typeof name !== 'string') { throw new Error('A subscription name is required.'); @@ -754,7 +754,7 @@ export class PubSub { reqOpts, gaxOpts: gaxOpts as CallOptions, }, - callback! + callback!, ); } @@ -857,7 +857,7 @@ export class PubSub { */ async *listSchemas( view: SchemaView = SchemaViews.Basic, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { const client = await this.getSchemaClient(); const query = { @@ -923,7 +923,7 @@ export class PubSub { getSnapshots(options: PageOptions, callback: GetSnapshotsCallback): void; getSnapshots( optsOrCallback?: PageOptions | GetSnapshotsCallback, - callback?: GetSnapshotsCallback + callback?: GetSnapshotsCallback, ): void | Promise { const options = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -932,7 +932,7 @@ export class PubSub { { project: PubSub.formatName_(this.projectId), }, - options + options, ); delete reqOpts.gaxOpts; @@ -942,7 +942,7 @@ export class PubSub { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); this.request< @@ -964,12 +964,12 @@ export class PubSub { const snapshotInstance = this.snapshot(snapshot.name!); snapshotInstance.metadata = snapshot; return snapshotInstance; - } + }, ); } callback!(err, snapshots!, ...args); - } + }, ); } @@ -1033,16 +1033,16 @@ export class PubSub { * ``` */ getSubscriptions( - options?: GetSubscriptionsOptions + options?: GetSubscriptionsOptions, ): Promise; getSubscriptions(callback: GetSubscriptionsCallback): void; getSubscriptions( options: GetSubscriptionsOptions, - callback: GetSubscriptionsCallback + callback: GetSubscriptionsCallback, ): void; getSubscriptions( optsOrCallback?: GetSubscriptionsOptions | GetSubscriptionsCallback, - callback?: GetSubscriptionsCallback + callback?: GetSubscriptionsCallback, ): void | Promise { const options = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -1054,12 +1054,12 @@ export class PubSub { } return topic.getSubscriptions( options, - callback as GetTopicSubscriptionsCallback + callback as GetTopicSubscriptionsCallback, ); } const reqOpts = Object.assign( {}, - options + options, ) as google.pubsub.v1.IListSubscriptionsRequest; reqOpts.project = 'projects/' + this.projectId; @@ -1070,7 +1070,7 @@ export class PubSub { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); this.request< @@ -1095,7 +1095,7 @@ export class PubSub { } (callback as GetAllSubscriptionsCallback)(err, subscriptions!, ...args); - } + }, ); } @@ -1162,7 +1162,7 @@ export class PubSub { getTopics(options: PageOptions, callback: GetTopicsCallback): void; getTopics( optsOrCallback?: PageOptions | GetTopicsCallback, - callback?: GetTopicsCallback + callback?: GetTopicsCallback, ): void | Promise { const options = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -1171,7 +1171,7 @@ export class PubSub { { project: 'projects/' + this.projectId, }, - options + options, ); delete reqOpts.gaxOpts; @@ -1181,7 +1181,7 @@ export class PubSub { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); this.request( @@ -1203,7 +1203,7 @@ export class PubSub { } callback!(err, topics!, ...args); - } + }, ); } @@ -1272,7 +1272,7 @@ export class PubSub { getClient_(config: GetClientConfig, callback: GetClientCallback) { this.getClientAsync_(config).then( client => callback(null, client), - callback + callback, ); } /** @@ -1476,7 +1476,7 @@ export class PubSub { parent: this.name, schema, }, - gaxOpts + gaxOpts, ); } diff --git a/src/schema.ts b/src/schema.ts index a332d0aff..f2c97cb67 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -122,7 +122,7 @@ export class Schema { async create( type: SchemaType, definition: string, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise { const name = await this.getName(); await this.pubsub.createSchema(name, type, definition, gaxOpts); @@ -142,7 +142,7 @@ export class Schema { */ async get( view: SchemaView = SchemaViews.Full, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise { const client = await this.pubsub.getSchemaClient(); const name = await this.getName(); @@ -151,7 +151,7 @@ export class Schema { name, view, }, - gaxOpts + gaxOpts, ); return schema; @@ -173,7 +173,7 @@ export class Schema { { name, }, - gaxOpts + gaxOpts, ); } @@ -200,7 +200,7 @@ export class Schema { encoding: | google.pubsub.v1.Encoding | keyof typeof google.pubsub.v1.Encoding, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise { const client = await this.pubsub.getSchemaClient(); const name = await this.getName(); @@ -212,7 +212,7 @@ export class Schema { message, encoding, }, - gaxOpts + gaxOpts, ); } diff --git a/src/snapshot.ts b/src/snapshot.ts index da907ef60..1924015e5 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -145,7 +145,7 @@ export class Snapshot { method: 'deleteSnapshot', reqOpts, }, - callback! + callback!, ); } @@ -201,11 +201,11 @@ export class Snapshot { create(gaxOpts: CallOptions, callback: CreateSnapshotCallback): void; create( optsOrCallback?: CallOptions | CreateSnapshotCallback, - callback?: CreateSnapshotCallback + callback?: CreateSnapshotCallback, ): void | Promise { if (!(this.parent instanceof Subscription)) { throw new Error( - 'This is only available if you accessed this object through Subscription#snapshot' + 'This is only available if you accessed this object through Subscription#snapshot', ); } @@ -222,7 +222,7 @@ export class Snapshot { } Object.assign(this, snapshot); callback!(null, this, resp); - } + }, ); } @@ -258,11 +258,11 @@ export class Snapshot { seek(gaxOpts: CallOptions, callback: SeekCallback): void; seek( gaxOpts?: CallOptions | SeekCallback, - callback?: SeekCallback + callback?: SeekCallback, ): void | Promise { if (!(this.parent instanceof Subscription)) { throw new Error( - 'This is only available if you accessed this object through Subscription#snapshot' + 'This is only available if you accessed this object through Subscription#snapshot', ); } return this.parent.seek(this.name, gaxOpts! as CallOptions, callback!); diff --git a/src/subscriber.ts b/src/subscriber.ts index 834165c7d..156ebfe55 100644 --- a/src/subscriber.ts +++ b/src/subscriber.ts @@ -152,7 +152,7 @@ export class SubscriberSpans { schedulerStart() { if (!this.scheduler) { this.scheduler = tracing.PubsubSpans.createReceiveSchedulerSpan( - this.parent + this.parent, ); } } @@ -171,7 +171,7 @@ export class SubscriberSpans { if (!this.processing) { this.processing = tracing.PubsubSpans.createReceiveProcessSpan( this.parent, - subName + subName, ); } } @@ -283,7 +283,7 @@ export class Message implements tracing.MessageWithAttributes { */ constructor( sub: Subscriber, - {ackId, message, deliveryAttempt}: google.pubsub.v1.IReceivedMessage + {ackId, message, deliveryAttempt}: google.pubsub.v1.IReceivedMessage, ) { /** * This ID is used to acknowledge the message. @@ -406,7 +406,7 @@ export class Message implements tracing.MessageWithAttributes { this._handled = true; this.subSpans.ackCall(); this.subSpans.processingEnd(); - this._subscriber.ack(this); + void this._subscriber.ack(this); } } @@ -456,7 +456,7 @@ export class Message implements tracing.MessageWithAttributes { modAck(deadline: number): void { if (!this._handled) { this.subSpans.modAckCall(Duration.from({seconds: deadline})); - this._subscriber.modAck(this, deadline); + void this._subscriber.modAck(this, deadline); } } @@ -506,7 +506,7 @@ export class Message implements tracing.MessageWithAttributes { this._handled = true; this.subSpans.nackCall(); this.subSpans.processingEnd(); - this._subscriber.nack(this); + void this._subscriber.nack(this); } } @@ -560,6 +560,8 @@ export class Message implements tracing.MessageWithAttributes { * ever have, while it's under library control. * @property {Duration} [maxAckDeadline] The maximum time that ackDeadline should * ever have, while it's under library control. + * @property {Duration} [maxExtensionTime] The maximum time that ackDeadline should + * ever have, while it's under library control. * @property {BatchOptions} [batching] Request batching options; this is for * batching acks and modacks being sent back to the server. * @property {FlowControlOptions} [flowControl] Flow control options. @@ -569,19 +571,13 @@ export class Message implements tracing.MessageWithAttributes { * @property {MessageStreamOptions} [streamingOptions] Streaming options. */ export interface SubscriberOptions { - /** @deprecated Use minAckDeadline and maxAckDeadline. */ - ackDeadline?: number; - minAckDeadline?: Duration; maxAckDeadline?: Duration; + maxExtensionTime?: Duration; batching?: BatchOptions; flowControl?: FlowControlOptions; useLegacyFlowControl?: boolean; streamingOptions?: MessageStreamOptions; - - /** @deprecated Unset this and instantiate a tracer; support will be - * enabled automatically. */ - enableOpenTelemetryTracing?: boolean; } const minAckDeadlineForExactlyOnceDelivery = Duration.from({seconds: 60}); @@ -601,10 +597,10 @@ export class Subscriber extends EventEmitter { maxBytes: number; useLegacyFlowControl: boolean; isOpen: boolean; + maxExtensionTime: Duration; private _acks!: AckQueue; private _histogram: Histogram; private _inventory!: LeaseManager; - private _useLegacyOpenTelemetry: boolean; private _latencies: Histogram; private _modAcks!: ModAckQueue; private _name!: string; @@ -617,12 +613,13 @@ export class Subscriber extends EventEmitter { constructor(subscription: Subscription, options = {}) { super(); - this.ackDeadline = defaultOptions.subscription.ackDeadline; + this.ackDeadline = + defaultOptions.subscription.startingAckDeadline.totalOf('second'); this.maxMessages = defaultOptions.subscription.maxOutstandingMessages; this.maxBytes = defaultOptions.subscription.maxOutstandingBytes; + this.maxExtensionTime = defaultOptions.subscription.maxExtensionTime; this.useLegacyFlowControl = false; this.isOpen = false; - this._useLegacyOpenTelemetry = false; this._histogram = new Histogram({min: 10, max: 600}); this._latencies = new Histogram(); this._subscription = subscription; @@ -718,7 +715,7 @@ export class Subscriber extends EventEmitter { ? 60 : 10; this._stream.setStreamAckDeadline( - Duration.from({seconds: subscriptionAckDeadlineSeconds}) + Duration.from({seconds: subscriptionAckDeadlineSeconds}), ); } } @@ -881,7 +878,7 @@ export class Subscriber extends EventEmitter { */ async modAckWithResponse( message: Message, - deadline: number + deadline: number, ): Promise { const startTime = Date.now(); @@ -951,7 +948,7 @@ export class Subscriber extends EventEmitter { this._stream.start().catch(err => { this.emit('error', err); - this.close(); + void this.close(); }); this.isOpen = true; @@ -966,17 +963,6 @@ export class Subscriber extends EventEmitter { setOptions(options: SubscriberOptions): void { this._options = options; - this._useLegacyOpenTelemetry = options.enableOpenTelemetryTracing || false; - - // The user-set ackDeadline value basically pegs the extension time. - // We'll emulate it by overwriting min/max. - const passedAckDeadline = options.ackDeadline; - if (passedAckDeadline !== undefined) { - this.ackDeadline = passedAckDeadline; - options.minAckDeadline = Duration.from({seconds: passedAckDeadline}); - options.maxAckDeadline = Duration.from({seconds: passedAckDeadline}); - } - this.useLegacyFlowControl = options.useLegacyFlowControl || false; if (options.flowControl) { this.maxMessages = @@ -999,13 +985,25 @@ export class Subscriber extends EventEmitter { options.streamingOptions.maxStreams = Math.min( maxStreams, - this.maxMessages + this.maxMessages, ); } if (this._inventory) { this._inventory.setOptions(this._options.flowControl!); } + + this.updateAckDeadline(); + } + + /** + * Retrieves our effective options. This is mostly for unit test use. + * + * @private + * @returns {SubscriberOptions} The options. + */ + getOptions(): SubscriberOptions { + return this._options; } /** @@ -1015,11 +1013,9 @@ export class Subscriber extends EventEmitter { * @private */ private createParentSpan(message: Message): void { - const enabled = tracing.isEnabled({ - enableOpenTelemetryTracing: this._useLegacyOpenTelemetry, - }); + const enabled = tracing.isEnabled(); if (enabled) { - tracing.extractSpan(message, this.name, enabled); + tracing.extractSpan(message, this.name); } } @@ -1058,7 +1054,7 @@ export class Subscriber extends EventEmitter { // lease on the message before actually leasing it. message.subSpans.modAckStart( Duration.from({seconds: this.ackDeadline}), - true + true, ); message .modAckWithResponse(this.ackDeadline) @@ -1076,7 +1072,7 @@ export class Subscriber extends EventEmitter { } else { message.subSpans.modAckStart( Duration.from({seconds: this.ackDeadline}), - true + true, ); message.modAck(this.ackDeadline); message.subSpans.modAckEnd(); @@ -1106,12 +1102,12 @@ export class Subscriber extends EventEmitter { if (this._acks.numPendingRequests) { promises.push(this._acks.onFlush()); - this._acks.flush(); + await this._acks.flush(); } if (this._modAcks.numPendingRequests) { promises.push(this._modAcks.onFlush()); - this._modAcks.flush(); + await this._modAcks.flush(); } if (this._acks.numInFlightRequests) { diff --git a/src/subscription.ts b/src/subscription.ts index 0df829a67..6a5f6023e 100644 --- a/src/subscription.ts +++ b/src/subscription.ts @@ -103,11 +103,11 @@ export declare interface Subscription { // Only used internally. on( event: 'newListener', - listener: (event: string | symbol, listener: Function) => void + listener: (event: string | symbol, listener: Function) => void, ): this; on( event: 'removeListener', - listener: (event: string | symbol, listener: Function) => void + listener: (event: string | symbol, listener: Function) => void, ): this; // Catch-all. If you get an error about this line, it means you're @@ -422,20 +422,20 @@ export class Subscription extends EventEmitter { * ``` */ create( - options?: CreateSubscriptionOptions + options?: CreateSubscriptionOptions, ): Promise; create(callback: CreateSubscriptionCallback): void; create( options: CreateSubscriptionOptions, - callback: CreateSubscriptionCallback + callback: CreateSubscriptionCallback, ): void; create( optsOrCallback?: CreateSubscriptionOptions | CreateSubscriptionCallback, - callback?: CreateSubscriptionCallback + callback?: CreateSubscriptionCallback, ): void | Promise { if (!this.topic) { throw new Error( - 'Subscriptions can only be created when accessed through Topics' + 'Subscriptions can only be created when accessed through Topics', ); } @@ -454,7 +454,7 @@ export class Subscription extends EventEmitter { } Object.assign(this, sub); callback!(null, this, resp); - } + }, ); } @@ -505,18 +505,18 @@ export class Subscription extends EventEmitter { */ createSnapshot( name: string, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; createSnapshot(name: string, callback: CreateSnapshotCallback): void; createSnapshot( name: string, gaxOpts: CallOptions, - callback: CreateSnapshotCallback + callback: CreateSnapshotCallback, ): void; createSnapshot( name: string, optsOrCallback?: CallOptions | CreateSnapshotCallback, - callback?: CreateSnapshotCallback + callback?: CreateSnapshotCallback, ): void | Promise { if (typeof name !== 'string') { throw new Error('A name is required to create a snapshot.'); @@ -543,7 +543,7 @@ export class Subscription extends EventEmitter { } snapshot.metadata = resp!; callback!(null, snapshot, resp!); - } + }, ); } @@ -583,7 +583,7 @@ export class Subscription extends EventEmitter { delete(gaxOpts: CallOptions, callback: EmptyCallback): void; delete( optsOrCallback?: CallOptions | EmptyCallback, - callback?: EmptyCallback + callback?: EmptyCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -593,7 +593,7 @@ export class Subscription extends EventEmitter { }; if (this.isOpen) { - this._subscriber.close(); + void this._subscriber.close(); } this.request( @@ -603,7 +603,7 @@ export class Subscription extends EventEmitter { reqOpts, gaxOpts, }, - callback! + callback!, ); } @@ -749,7 +749,7 @@ export class Subscription extends EventEmitter { get(gaxOpts: GetSubscriptionOptions, callback: GetSubscriptionCallback): void; get( optsOrCallback?: GetSubscriptionOptions | GetSubscriptionCallback, - callback?: GetSubscriptionCallback + callback?: GetSubscriptionCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -815,11 +815,11 @@ export class Subscription extends EventEmitter { getMetadata(callback: GetSubscriptionMetadataCallback): void; getMetadata( gaxOpts: CallOptions, - callback: GetSubscriptionMetadataCallback + callback: GetSubscriptionMetadataCallback, ): void; getMetadata( optsOrCallback?: CallOptions | GetSubscriptionMetadataCallback, - callback?: GetSubscriptionMetadataCallback + callback?: GetSubscriptionMetadataCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -840,7 +840,7 @@ export class Subscription extends EventEmitter { this.metadata = apiResponse!; } callback!(err!, apiResponse!); - } + }, ); } @@ -904,18 +904,18 @@ export class Subscription extends EventEmitter { */ modifyPushConfig( config: PushConfig, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; modifyPushConfig(config: PushConfig, callback: EmptyCallback): void; modifyPushConfig( config: PushConfig, gaxOpts: CallOptions, - callback: EmptyCallback + callback: EmptyCallback, ): void; modifyPushConfig( config: PushConfig, optsOrCallback?: CallOptions | EmptyCallback, - callback?: EmptyCallback + callback?: EmptyCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -932,7 +932,7 @@ export class Subscription extends EventEmitter { reqOpts, gaxOpts, }, - callback! + callback!, ); } @@ -1009,12 +1009,12 @@ export class Subscription extends EventEmitter { seek( snapshot: string | Date, gaxOpts: CallOptions, - callback: SeekCallback + callback: SeekCallback, ): void; seek( snapshot: string | Date, optsOrCallback?: CallOptions | SeekCallback, - callback?: SeekCallback + callback?: SeekCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -1042,7 +1042,7 @@ export class Subscription extends EventEmitter { reqOpts, gaxOpts, }, - callback! + callback!, ); } @@ -1086,21 +1086,21 @@ export class Subscription extends EventEmitter { */ setMetadata( metadata: SubscriptionMetadata, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; setMetadata( metadata: SubscriptionMetadata, - callback: SetSubscriptionMetadataCallback + callback: SetSubscriptionMetadataCallback, ): void; setMetadata( metadata: SubscriptionMetadata, gaxOpts: CallOptions, - callback: SetSubscriptionMetadataCallback + callback: SetSubscriptionMetadataCallback, ): void; setMetadata( metadata: SubscriptionMetadata, optsOrCallback?: CallOptions | SetSubscriptionMetadataCallback, - callback?: SetSubscriptionMetadataCallback + callback?: SetSubscriptionMetadataCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -1121,7 +1121,7 @@ export class Subscription extends EventEmitter { reqOpts, gaxOpts, }, - callback! + callback!, ); } /** @@ -1164,7 +1164,7 @@ export class Subscription extends EventEmitter { this.on('removeListener', () => { if (this.isOpen && this.listenerCount('message') === 0) { - this._subscriber.close(); + void this._subscriber.close(); } }); } @@ -1174,7 +1174,7 @@ export class Subscription extends EventEmitter { * @private */ static formatMetadata_( - metadata: SubscriptionMetadata + metadata: SubscriptionMetadata, ): google.pubsub.v1.ISubscription { const formatted = extend(true, {}, metadata); diff --git a/src/telemetry-tracing.ts b/src/telemetry-tracing.ts index 422b2d904..137dfc38d 100644 --- a/src/telemetry-tracing.ts +++ b/src/telemetry-tracing.ts @@ -28,7 +28,6 @@ import { Link, } from '@opentelemetry/api'; import {Attributes, PubsubMessage} from './publisher/pubsub-message'; -import {PublishOptions} from './publisher/index'; import {Duration} from './temporal'; export {Span}; @@ -65,13 +64,6 @@ export enum OpenTelemetryLevel { */ None = 0, - /** - * Legacy: We found a trace provider, but the user also specified the old - * manual enable flag; this will trigger the legacy attribute being included. - * The modern propagation attribute will _also_ be included. - */ - Legacy = 1, - /** * Modern: We will only inject/extract the modern propagation attribute. */ @@ -96,26 +88,11 @@ export function setGloballyEnabled(enabled: boolean) { * Tries to divine what sort of OpenTelemetry we're supporting. See the enum * for the meaning of the values, and other notes. * - * Legacy OTel is no longer officially supported, but we don't want to - * break anyone at a non-major. - * * @private * @internal */ -export function isEnabled( - publishSettings?: PublishOptions -): OpenTelemetryLevel { - // If we're not enabled, skip everything. - if (!globallyEnabled) { - return OpenTelemetryLevel.None; - } - - if (publishSettings?.enableOpenTelemetryTracing) { - return OpenTelemetryLevel.Legacy; - } - - // Enable modern support. - return OpenTelemetryLevel.Modern; +export function isEnabled(): OpenTelemetryLevel { + return globallyEnabled ? OpenTelemetryLevel.Modern : OpenTelemetryLevel.None; } /** @@ -128,7 +105,6 @@ export function isEnabled( * or subscriber span, depending on the context. * * @private - * @internal */ export interface MessageWithAttributes { attributes?: Attributes | null | undefined; @@ -167,7 +143,7 @@ export class PubsubMessageGet { get( carrier: MessageWithAttributes, - key: string + key: string, ): string | string[] | undefined { return carrier?.attributes?.[this.attributeName(key)]; } @@ -224,7 +200,7 @@ export interface SpanAttributes { * @internal */ export function spanContextToContext( - parent?: SpanContext + parent?: SpanContext, ): Context | undefined { return parent ? trace.setSpanContext(context.active(), parent) : undefined; } @@ -242,14 +218,6 @@ export function spanContextToContext( */ export const modernAttributeName = 'googclient_traceparent'; -/** - * The old legacy attribute name. - * - * @private - * @internal - */ -export const legacyAttributeName = 'googclient_OpenTelemetrySpanContext'; - export interface AttributeParams { // Fully qualified. topicName?: string; @@ -328,7 +296,7 @@ export class PubsubSpans { static createAttributes( params: AttributeParams, message?: PubsubMessage, - caller?: string + caller?: string, ): SpanAttributes { const destinationName = params.topicName ?? params.subName; const destinationId = params.topicId ?? params.subId; @@ -383,7 +351,7 @@ export class PubsubSpans { static createPublisherSpan( message: PubsubMessage, topicName: string, - caller: string + caller: string, ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -420,7 +388,7 @@ export class PubsubSpans { message: PubsubMessage, subName: string, parent: Context | undefined, - caller: string + caller: string, ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -441,7 +409,7 @@ export class PubsubSpans { kind: SpanKind.CONSUMER, attributes, }, - parent + parent, ); } else { return getTracer().startSpan(name, { @@ -455,7 +423,7 @@ export class PubsubSpans { name: string, message?: PubsubMessage, parentSpan?: Span, - attributes?: SpanAttributes + attributes?: SpanAttributes, ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -469,7 +437,7 @@ export class PubsubSpans { kind: SpanKind.INTERNAL, attributes: attributes ?? {}, }, - spanContextToContext(parent.spanContext()) + spanContextToContext(parent.spanContext()), ); } else { return undefined; @@ -487,7 +455,7 @@ export class PubsubSpans { static createPublishRpcSpan( messages: MessageWithAttributes[], topicName: string, - caller: string + caller: string, ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -496,7 +464,7 @@ export class PubsubSpans { const spanAttributes = PubsubSpans.createAttributes( getTopicInfo(topicName), undefined, - caller + caller, ); const links: Link[] = messages .filter(m => m.parentSpan && isSampled(m.parentSpan)) @@ -509,7 +477,7 @@ export class PubsubSpans { attributes: spanAttributes, links, }, - ROOT_CONTEXT + ROOT_CONTEXT, ); span?.setAttribute('messaging.batch.message_count', messages.length); if (span) { @@ -527,7 +495,7 @@ export class PubsubSpans { static createAckRpcSpan( messageSpans: (Span | undefined)[], subName: string, - caller: string + caller: string, ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -538,7 +506,7 @@ export class PubsubSpans { const spanAttributes = PubsubSpans.createAttributes( subInfo, undefined, - caller + caller, ); const links: Link[] = messageSpans .filter(m => m && isSampled(m)) @@ -551,7 +519,7 @@ export class PubsubSpans { attributes: spanAttributes, links, }, - ROOT_CONTEXT + ROOT_CONTEXT, ); span?.setAttribute('messaging.batch.message_count', messageSpans.length); @@ -575,7 +543,7 @@ export class PubsubSpans { type: 'modack' | 'nack', caller: string, deadline?: Duration, - isInitial?: boolean + isInitial?: boolean, ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -586,7 +554,7 @@ export class PubsubSpans { const spanAttributes = PubsubSpans.createAttributes( subInfo, undefined, - caller + caller, ); const links: Link[] = messageSpans .filter(m => m && isSampled(m)) @@ -599,7 +567,7 @@ export class PubsubSpans { attributes: spanAttributes, links, }, - ROOT_CONTEXT + ROOT_CONTEXT, ); span?.setAttribute('messaging.batch.message_count', messageSpans.length); @@ -617,7 +585,7 @@ export class PubsubSpans { if (deadline) { span?.setAttribute( 'messaging.gcp_pubsub.message.ack_deadline_seconds', - deadline.totalOf('second') + deadline.totalOf('second'), ); } @@ -629,28 +597,28 @@ export class PubsubSpans { } static createReceiveFlowSpan( - message: MessageWithAttributes + message: MessageWithAttributes, ): Span | undefined { return PubsubSpans.createChildSpan( 'subscriber concurrency control', - message + message, ); } static createReceiveSchedulerSpan( - message: MessageWithAttributes + message: MessageWithAttributes, ): Span | undefined { return PubsubSpans.createChildSpan('subscriber scheduler', message); } static createReceiveProcessSpan( message: MessageWithAttributes, - subName: string + subName: string, ): Span | undefined { const subInfo = getSubscriptionInfo(subName); return PubsubSpans.createChildSpan( `${subInfo.subId ?? subName} process`, - message + message, ); } @@ -669,7 +637,7 @@ export class PubsubEvents { static addEvent( text: string, message: MessageWithAttributes, - attributes?: Attributes + attributes?: Attributes, ): void { const parent = message.parentSpan; if (!parent) { @@ -723,7 +691,7 @@ export class PubsubEvents { // User-called modAcks are never initial ones. span.addEvent('modack called', { 'messaging.gcp_pubsub.modack_deadline_seconds': `${deadline.totalOf( - 'second' + 'second', )}`, 'messaging.gcp_pubsub.is_receipt_modack': 'false', }); @@ -732,11 +700,11 @@ export class PubsubEvents { static modAckStart( message: MessageWithAttributes, deadline: Duration, - isInitial: boolean + isInitial: boolean, ) { PubsubEvents.addEvent('modack start', message, { 'messaging.gcp_pubsub.modack_deadline_seconds': `${deadline.totalOf( - 'second' + 'second', )}`, 'messaging.gcp_pubsub.is_receipt_modack': isInitial ? 'true' : 'false', }); @@ -762,11 +730,7 @@ export class PubsubEvents { * @private * @internal */ -export function injectSpan( - span: Span, - message: MessageWithAttributes, - enabled: OpenTelemetryLevel -): void { +export function injectSpan(span: Span, message: MessageWithAttributes): void { if (!globallyEnabled) { return; } @@ -777,24 +741,12 @@ export function injectSpan( if (message.attributes[modernAttributeName]) { console.warn( - `${modernAttributeName} key set as message attribute, but will be overridden.` + `${modernAttributeName} key set as message attribute, but will be overridden.`, ); delete message.attributes[modernAttributeName]; } - // If we're in legacy mode, add that header as well. - if (enabled === OpenTelemetryLevel.Legacy) { - if (message.attributes[legacyAttributeName]) { - console.warn( - `${legacyAttributeName} key set as message attribute, but will be overridden.` - ); - } - message.attributes[legacyAttributeName] = JSON.stringify( - span.spanContext() - ); - } - // Always do propagation injection with the trace context. const context = trace.setSpanContext(ROOT_CONTEXT, span.spanContext()); propagation.inject(context, message, pubsubSetter); @@ -820,9 +772,7 @@ export function containsSpanContext(message: MessageWithAttributes): boolean { } const keys = Object.getOwnPropertyNames(message.attributes); - return !!keys.find( - n => n === legacyAttributeName || n === modernAttributeName - ); + return !!keys.find(n => n === modernAttributeName); } /** @@ -838,7 +788,6 @@ export function containsSpanContext(message: MessageWithAttributes): boolean { export function extractSpan( message: MessageWithAttributes, subName: string, - enabled: OpenTelemetryLevel ): Span | undefined { if (!globallyEnabled) { return undefined; @@ -852,64 +801,16 @@ export function extractSpan( let context: Context | undefined; - if (enabled === OpenTelemetryLevel.Legacy) { - // Only prefer the legacy attributes to no trace context attribute. - if ( - keys.includes(legacyAttributeName) && - !keys.includes(modernAttributeName) - ) { - const legacyValue = message.attributes?.[legacyAttributeName]; - if (legacyValue) { - const parentSpanContext: SpanContext | undefined = legacyValue - ? JSON.parse(legacyValue) - : undefined; - if (parentSpanContext) { - context = spanContextToContext(parentSpanContext); - } - } - } - } else { - if (keys.includes(modernAttributeName)) { - context = propagation.extract(ROOT_CONTEXT, message, pubsubGetter); - } + if (keys.includes(modernAttributeName)) { + context = propagation.extract(ROOT_CONTEXT, message, pubsubGetter); } const span = PubsubSpans.createReceiveSpan( message, subName, context, - 'extractSpan' + 'extractSpan', ); message.parentSpan = span; return span; } - -// Since these were exported on the main Pub/Sub index in the previous -// version, we have to export them until the next major. -export const legacyExports = { - /** - * @deprecated - * Use the new telemetry functionality instead; see the updated OpenTelemetry - * sample for an example. - */ - createSpan: function ( - spanName: string, - kind: SpanKind, - attributes?: SpanAttributes, - parent?: SpanContext - ): Span { - if (!globallyEnabled) { - // This isn't great, but it's the fact of the situation. - return undefined as unknown as Span; - } else { - return getTracer().startSpan( - spanName, - { - kind, - attributes, - }, - parent ? trace.setSpanContext(context.active(), parent) : undefined - ); - } - }, -}; diff --git a/src/topic.ts b/src/topic.ts index e0a5d03b6..633c5f4cb 100644 --- a/src/topic.ts +++ b/src/topic.ts @@ -113,7 +113,7 @@ export class Topic { metadata?: TopicMetadata; publisher: Publisher; getSubscriptionsStream = paginator.streamify( - 'getSubscriptions' + 'getSubscriptions', ) as () => ObjectStream; constructor(pubsub: PubSub, name: string, options?: PublishOptions) { @@ -239,7 +239,7 @@ export class Topic { create(gaxOpts: CallOptions, callback: CreateTopicCallback): void; create( optsOrCallback?: CallOptions | CreateTopicCallback, - callback?: CreateTopicCallback + callback?: CreateTopicCallback, ): Promise | void { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -289,17 +289,17 @@ export class Topic { createSubscription(name: string, callback: CreateSubscriptionCallback): void; createSubscription( name: string, - options?: CreateSubscriptionOptions + options?: CreateSubscriptionOptions, ): Promise; createSubscription( name: string, options: CreateSubscriptionOptions, - callback: CreateSubscriptionCallback + callback: CreateSubscriptionCallback, ): void; createSubscription( name: string, optsOrCallback?: CreateSubscriptionOptions | CreateSubscriptionCallback, - callback?: CreateSubscriptionCallback + callback?: CreateSubscriptionCallback, ): void | Promise { const options = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -308,7 +308,7 @@ export class Topic { this, name, options as CreateSubscriptionOptions, - callback! + callback!, ); } @@ -346,7 +346,7 @@ export class Topic { delete(gaxOpts: CallOptions, callback: EmptyCallback): void; delete( optsOrCallback?: CallOptions | EmptyCallback, - callback?: EmptyCallback + callback?: EmptyCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -362,7 +362,7 @@ export class Topic { reqOpts, gaxOpts: gaxOpts as CallOptions, }, - callback! + callback!, ); } @@ -460,7 +460,7 @@ export class Topic { get(gaxOpts: GetTopicOptions, callback: GetTopicCallback): void; get( optsOrCallback?: GetTopicOptions | GetTopicCallback, - callback?: GetTopicCallback + callback?: GetTopicCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -522,7 +522,7 @@ export class Topic { getMetadata(gaxOpts?: CallOptions): Promise; getMetadata( optsOrCallback?: CallOptions | GetTopicMetadataCallback, - callback?: GetTopicMetadataCallback + callback?: GetTopicMetadataCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -543,7 +543,7 @@ export class Topic { this.metadata = apiResponse!; } callback!(err, apiResponse!); - } + }, ); } @@ -588,14 +588,14 @@ export class Topic { getSubscriptions(callback: GetTopicSubscriptionsCallback): void; getSubscriptions( options: PageOptions, - callback: GetTopicSubscriptionsCallback + callback: GetTopicSubscriptionsCallback, ): void; getSubscriptions( - options?: PageOptions + options?: PageOptions, ): Promise; getSubscriptions( optsOrCallback?: PageOptions | GetTopicSubscriptionsCallback, - callback?: GetTopicSubscriptionsCallback + callback?: GetTopicSubscriptionsCallback, ): void | Promise { const options = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -605,7 +605,7 @@ export class Topic { { topic: this.name, }, - options as SubscriptionOptions + options as SubscriptionOptions, ); delete (reqOpts as PageOptions).gaxOpts; @@ -615,7 +615,7 @@ export class Topic { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); this.request( @@ -633,7 +633,7 @@ export class Topic { } callback!(err, subscriptions!, ...args); - } + }, ); } @@ -687,12 +687,12 @@ export class Topic { publish( data: Buffer, attributes: Attributes, - callback: PublishCallback + callback: PublishCallback, ): void; publish( data: Buffer, attrsOrCb?: Attributes | PublishCallback, - callback?: PublishCallback + callback?: PublishCallback, ): Promise | void { const attributes = typeof attrsOrCb === 'object' ? attrsOrCb : {}; callback = typeof attrsOrCb === 'function' ? attrsOrCb : callback; @@ -753,12 +753,12 @@ export class Topic { publishJSON( json: object, attributes: Attributes, - callback: PublishCallback + callback: PublishCallback, ): void; publishJSON( json: object, attrsOrCb?: Attributes | PublishCallback, - callback?: PublishCallback + callback?: PublishCallback, ): Promise | void { if (!json || typeof json !== 'object') { throw new Error('First parameter should be an object.'); @@ -832,7 +832,7 @@ export class Topic { publishMessage(message: MessageOptions, callback: PublishCallback): void; publishMessage( message: MessageOptions, - callback?: PublishCallback + callback?: PublishCallback, ): Promise | void { // Make a copy to ensure that any changes we make to it will not // propagate up to the user's data. @@ -940,18 +940,18 @@ export class Topic { */ setMetadata( options: TopicMetadata, - gaxOpts?: CallOptions + gaxOpts?: CallOptions, ): Promise; setMetadata(options: TopicMetadata, callback: SetTopicMetadataCallback): void; setMetadata( options: TopicMetadata, gaxOpts: CallOptions, - callback: SetTopicMetadataCallback + callback: SetTopicMetadataCallback, ): void; setMetadata( options: TopicMetadata, optsOrCallback?: CallOptions | SetTopicMetadataCallback, - callback?: SetTopicMetadataCallback + callback?: SetTopicMetadataCallback, ): void | Promise { const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {}; callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback; @@ -967,7 +967,7 @@ export class Topic { reqOpts, gaxOpts, }, - callback! + callback!, ); } diff --git a/src/util.ts b/src/util.ts index 60cbdc205..04bfb270d 100644 --- a/src/util.ts +++ b/src/util.ts @@ -30,7 +30,7 @@ export function promisifySome( class_: Function, classProto: T, methods: (keyof T)[], - options?: PromisifyOptions + options?: PromisifyOptions, ): void { methods.forEach(methodName => { // Do the same stream checks as promisifyAll(). diff --git a/src/v1/publisher_client.ts b/src/v1/publisher_client.ts index f8ce9d942..ae3a4f591 100644 --- a/src/v1/publisher_client.ts +++ b/src/v1/publisher_client.ts @@ -31,6 +31,7 @@ import type { import {Transform} from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging} from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -56,6 +57,8 @@ export class PublisherClient { private _defaults: {[method: string]: gax.CallSettings}; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('pubsub'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -91,7 +94,7 @@ export class PublisherClient { * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports - * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. @@ -110,7 +113,7 @@ export class PublisherClient { */ constructor( opts?: ClientOptions, - gaxInstance?: typeof gax | typeof gax.fallback + gaxInstance?: typeof gax | typeof gax.fallback, ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof PublisherClient; @@ -120,7 +123,7 @@ export class PublisherClient { opts?.universe_domain !== opts?.universeDomain ) { throw new Error( - 'Please set either universe_domain or universeDomain, but not both.' + 'Please set either universe_domain or universeDomain, but not both.', ); } const universeDomainEnvVar = @@ -145,9 +148,6 @@ export class PublisherClient { (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); - // Request numeric enum values if REST transport is used. - opts.numericEnums = true; - // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; @@ -205,19 +205,19 @@ export class PublisherClient { // Create useful helper objects for these. this.pathTemplates = { projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectTopicPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/topics/{topic}' + 'projects/{project}/topics/{topic}', ), schemaPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/schemas/{schema}' + 'projects/{project}/schemas/{schema}', ), snapshotPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/snapshots/{snapshot}' + 'projects/{project}/snapshots/{snapshot}', ), subscriptionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/subscriptions/{subscription}' + 'projects/{project}/subscriptions/{subscription}', ), }; @@ -228,33 +228,17 @@ export class PublisherClient { listTopics: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'topics' + 'topics', ), listTopicSubscriptions: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'subscriptions' + 'subscriptions', ), listTopicSnapshots: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'snapshots' - ), - }; - - const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); - // Some methods on this API support automatically batching - // requests; denote this. - - this.descriptors.batching = { - publish: new this._gaxModule.BundleDescriptor( - 'messages', - ['topic'], - 'message_ids', - this._gaxModule.GrpcClient.createByteLengthFunction( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - protoFilesRoot.lookupType('google.pubsub.v1.PubsubMessage') as any - ) + 'snapshots', ), }; @@ -263,7 +247,7 @@ export class PublisherClient { 'google.pubsub.v1.Publisher', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -297,12 +281,12 @@ export class PublisherClient { this.publisherStub = this._gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( - 'google.pubsub.v1.Publisher' + 'google.pubsub.v1.Publisher', ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.pubsub.v1.Publisher, this._opts, - this._providedCustomServicePath + this._providedCustomServicePath, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides @@ -330,18 +314,15 @@ export class PublisherClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); - const descriptor = - this.descriptors.page[methodName] || - this.descriptors.batching?.[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -362,7 +343,7 @@ export class PublisherClient { ) { process.emitWarning( 'Static servicePath is deprecated, please use the instance method instead.', - 'DeprecationWarning' + 'DeprecationWarning', ); } return 'pubsub.googleapis.com'; @@ -380,7 +361,7 @@ export class PublisherClient { ) { process.emitWarning( 'Static apiEndpoint is deprecated, please use the instance method instead.', - 'DeprecationWarning' + 'DeprecationWarning', ); } return 'pubsub.googleapis.com'; @@ -425,7 +406,7 @@ export class PublisherClient { * @returns {Promise} A promise that resolves to string containing the project ID. */ getProjectId( - callback?: Callback + callback?: Callback, ): Promise | void { if (callback) { this.auth.getProjectId(callback); @@ -481,16 +462,21 @@ export class PublisherClient { * Output only. An output-only field indicating the state of the topic. * @param {google.pubsub.v1.IngestionDataSourceSettings} [request.ingestionDataSourceSettings] * Optional. Settings for ingestion from a data source into this topic. + * @param {number[]} [request.messageTransforms] + * Optional. Transforms to be applied to messages published to the topic. + * Transforms are applied in the order specified. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing {@link protos.google.pubsub.v1.Topic|Topic}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.create_topic.js + * region_tag:pubsub_v1_generated_Publisher_CreateTopic_async */ createTopic( request?: protos.google.pubsub.v1.ITopic, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ITopic, @@ -505,7 +491,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.ITopic | null | undefined, {} | null | undefined - > + >, ): void; createTopic( request: protos.google.pubsub.v1.ITopic, @@ -513,7 +499,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.ITopic | null | undefined, {} | null | undefined - > + >, ): void; createTopic( request?: protos.google.pubsub.v1.ITopic, @@ -528,7 +514,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.ITopic | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ITopic, @@ -551,8 +537,34 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.createTopic(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createTopic request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ITopic, + protos.google.pubsub.v1.ITopic | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createTopic response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createTopic(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ITopic, + protos.google.pubsub.v1.ITopic | undefined, + {} | undefined, + ]) => { + this._log.info('createTopic response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Updates an existing topic by updating the fields specified in the update @@ -574,10 +586,12 @@ export class PublisherClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Topic|Topic}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.update_topic.js + * region_tag:pubsub_v1_generated_Publisher_UpdateTopic_async */ updateTopic( request?: protos.google.pubsub.v1.IUpdateTopicRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ITopic, @@ -592,7 +606,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.IUpdateTopicRequest | null | undefined, {} | null | undefined - > + >, ): void; updateTopic( request: protos.google.pubsub.v1.IUpdateTopicRequest, @@ -600,7 +614,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.IUpdateTopicRequest | null | undefined, {} | null | undefined - > + >, ): void; updateTopic( request?: protos.google.pubsub.v1.IUpdateTopicRequest, @@ -615,7 +629,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.IUpdateTopicRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ITopic, @@ -638,8 +652,34 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ 'topic.name': request.topic!.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateTopic(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateTopic request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ITopic, + protos.google.pubsub.v1.IUpdateTopicRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateTopic response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateTopic(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ITopic, + protos.google.pubsub.v1.IUpdateTopicRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateTopic response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic @@ -658,10 +698,12 @@ export class PublisherClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.PublishResponse|PublishResponse}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.publish.js + * region_tag:pubsub_v1_generated_Publisher_Publish_async */ publish( request?: protos.google.pubsub.v1.IPublishRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.IPublishResponse, @@ -676,7 +718,7 @@ export class PublisherClient { protos.google.pubsub.v1.IPublishResponse, protos.google.pubsub.v1.IPublishRequest | null | undefined, {} | null | undefined - > + >, ): void; publish( request: protos.google.pubsub.v1.IPublishRequest, @@ -684,7 +726,7 @@ export class PublisherClient { protos.google.pubsub.v1.IPublishResponse, protos.google.pubsub.v1.IPublishRequest | null | undefined, {} | null | undefined - > + >, ): void; publish( request?: protos.google.pubsub.v1.IPublishRequest, @@ -699,7 +741,7 @@ export class PublisherClient { protos.google.pubsub.v1.IPublishResponse, protos.google.pubsub.v1.IPublishRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.IPublishResponse, @@ -722,8 +764,34 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ topic: request.topic ?? '', }); - this.initialize(); - return this.innerApiCalls.publish(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('publish request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.IPublishResponse, + protos.google.pubsub.v1.IPublishRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('publish response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .publish(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.IPublishResponse, + protos.google.pubsub.v1.IPublishRequest | undefined, + {} | undefined, + ]) => { + this._log.info('publish response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Gets the configuration of a topic. @@ -739,10 +807,12 @@ export class PublisherClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Topic|Topic}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.get_topic.js + * region_tag:pubsub_v1_generated_Publisher_GetTopic_async */ getTopic( request?: protos.google.pubsub.v1.IGetTopicRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ITopic, @@ -757,7 +827,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.IGetTopicRequest | null | undefined, {} | null | undefined - > + >, ): void; getTopic( request: protos.google.pubsub.v1.IGetTopicRequest, @@ -765,7 +835,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.IGetTopicRequest | null | undefined, {} | null | undefined - > + >, ): void; getTopic( request?: protos.google.pubsub.v1.IGetTopicRequest, @@ -780,7 +850,7 @@ export class PublisherClient { protos.google.pubsub.v1.ITopic, protos.google.pubsub.v1.IGetTopicRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ITopic, @@ -803,8 +873,34 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ topic: request.topic ?? '', }); - this.initialize(); - return this.innerApiCalls.getTopic(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getTopic request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ITopic, + protos.google.pubsub.v1.IGetTopicRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getTopic response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getTopic(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ITopic, + protos.google.pubsub.v1.IGetTopicRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getTopic response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic @@ -824,10 +920,12 @@ export class PublisherClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.delete_topic.js + * region_tag:pubsub_v1_generated_Publisher_DeleteTopic_async */ deleteTopic( request?: protos.google.pubsub.v1.IDeleteTopicRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -842,7 +940,7 @@ export class PublisherClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteTopicRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteTopic( request: protos.google.pubsub.v1.IDeleteTopicRequest, @@ -850,7 +948,7 @@ export class PublisherClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteTopicRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteTopic( request?: protos.google.pubsub.v1.IDeleteTopicRequest, @@ -865,7 +963,7 @@ export class PublisherClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteTopicRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -888,8 +986,34 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ topic: request.topic ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteTopic(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteTopic request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteTopicRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteTopic response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteTopic(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteTopicRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTopic response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Detaches a subscription from this topic. All messages retained in the @@ -908,10 +1032,12 @@ export class PublisherClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.DetachSubscriptionResponse|DetachSubscriptionResponse}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.detach_subscription.js + * region_tag:pubsub_v1_generated_Publisher_DetachSubscription_async */ detachSubscription( request?: protos.google.pubsub.v1.IDetachSubscriptionRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.IDetachSubscriptionResponse, @@ -926,7 +1052,7 @@ export class PublisherClient { protos.google.pubsub.v1.IDetachSubscriptionResponse, protos.google.pubsub.v1.IDetachSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; detachSubscription( request: protos.google.pubsub.v1.IDetachSubscriptionRequest, @@ -934,7 +1060,7 @@ export class PublisherClient { protos.google.pubsub.v1.IDetachSubscriptionResponse, protos.google.pubsub.v1.IDetachSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; detachSubscription( request?: protos.google.pubsub.v1.IDetachSubscriptionRequest, @@ -949,7 +1075,7 @@ export class PublisherClient { protos.google.pubsub.v1.IDetachSubscriptionResponse, protos.google.pubsub.v1.IDetachSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.IDetachSubscriptionResponse, @@ -972,8 +1098,34 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.detachSubscription(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('detachSubscription request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.IDetachSubscriptionResponse, + protos.google.pubsub.v1.IDetachSubscriptionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('detachSubscription response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .detachSubscription(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.IDetachSubscriptionResponse, + protos.google.pubsub.v1.IDetachSubscriptionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('detachSubscription response %j', response); + return [response, options, rawResponse]; + }, + ); } /** @@ -1004,7 +1156,7 @@ export class PublisherClient { */ listTopics( request?: protos.google.pubsub.v1.IListTopicsRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ITopic[], @@ -1019,7 +1171,7 @@ export class PublisherClient { protos.google.pubsub.v1.IListTopicsRequest, protos.google.pubsub.v1.IListTopicsResponse | null | undefined, protos.google.pubsub.v1.ITopic - > + >, ): void; listTopics( request: protos.google.pubsub.v1.IListTopicsRequest, @@ -1027,7 +1179,7 @@ export class PublisherClient { protos.google.pubsub.v1.IListTopicsRequest, protos.google.pubsub.v1.IListTopicsResponse | null | undefined, protos.google.pubsub.v1.ITopic - > + >, ): void; listTopics( request?: protos.google.pubsub.v1.IListTopicsRequest, @@ -1042,7 +1194,7 @@ export class PublisherClient { protos.google.pubsub.v1.IListTopicsRequest, protos.google.pubsub.v1.IListTopicsResponse | null | undefined, protos.google.pubsub.v1.ITopic - > + >, ): Promise< [ protos.google.pubsub.v1.ITopic[], @@ -1065,12 +1217,38 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ project: request.project ?? '', }); - this.initialize(); - return this.innerApiCalls.listTopics(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListTopicsRequest, + protos.google.pubsub.v1.IListTopicsResponse | null | undefined, + protos.google.pubsub.v1.ITopic + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listTopics values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listTopics request %j', request); + return this.innerApiCalls + .listTopics(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.pubsub.v1.ITopic[], + protos.google.pubsub.v1.IListTopicsRequest | null, + protos.google.pubsub.v1.IListTopicsResponse, + ]) => { + this._log.info('listTopics values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listTopics`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.project @@ -1095,7 +1273,7 @@ export class PublisherClient { */ listTopicsStream( request?: protos.google.pubsub.v1.IListTopicsRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -1107,11 +1285,14 @@ export class PublisherClient { }); const defaultCallSettings = this._defaults['listTopics']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listTopics stream %j', request); return this.descriptors.page.listTopics.createStream( this.innerApiCalls.listTopics as GaxCall, request, - callSettings + callSettings, ); } @@ -1139,10 +1320,12 @@ export class PublisherClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.list_topics.js + * region_tag:pubsub_v1_generated_Publisher_ListTopics_async */ listTopicsAsync( request?: protos.google.pubsub.v1.IListTopicsRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -1154,11 +1337,14 @@ export class PublisherClient { }); const defaultCallSettings = this._defaults['listTopics']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listTopics iterate %j', request); return this.descriptors.page.listTopics.asyncIterate( this.innerApiCalls['listTopics'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -1189,7 +1375,7 @@ export class PublisherClient { */ listTopicSubscriptions( request?: protos.google.pubsub.v1.IListTopicSubscriptionsRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ string[], @@ -1206,7 +1392,7 @@ export class PublisherClient { | null | undefined, string - > + >, ): void; listTopicSubscriptions( request: protos.google.pubsub.v1.IListTopicSubscriptionsRequest, @@ -1216,7 +1402,7 @@ export class PublisherClient { | null | undefined, string - > + >, ): void; listTopicSubscriptions( request?: protos.google.pubsub.v1.IListTopicSubscriptionsRequest, @@ -1235,7 +1421,7 @@ export class PublisherClient { | null | undefined, string - > + >, ): Promise< [ string[], @@ -1258,16 +1444,40 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ topic: request.topic ?? '', }); - this.initialize(); - return this.innerApiCalls.listTopicSubscriptions( - request, - options, - callback - ); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListTopicSubscriptionsRequest, + | protos.google.pubsub.v1.IListTopicSubscriptionsResponse + | null + | undefined, + string + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listTopicSubscriptions values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listTopicSubscriptions request %j', request); + return this.innerApiCalls + .listTopicSubscriptions(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + string[], + protos.google.pubsub.v1.IListTopicSubscriptionsRequest | null, + protos.google.pubsub.v1.IListTopicSubscriptionsResponse, + ]) => { + this._log.info('listTopicSubscriptions values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listTopicSubscriptions`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.topic @@ -1292,7 +1502,7 @@ export class PublisherClient { */ listTopicSubscriptionsStream( request?: protos.google.pubsub.v1.IListTopicSubscriptionsRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -1304,11 +1514,14 @@ export class PublisherClient { }); const defaultCallSettings = this._defaults['listTopicSubscriptions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listTopicSubscriptions stream %j', request); return this.descriptors.page.listTopicSubscriptions.createStream( this.innerApiCalls.listTopicSubscriptions as GaxCall, request, - callSettings + callSettings, ); } @@ -1336,10 +1549,12 @@ export class PublisherClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.list_topic_subscriptions.js + * region_tag:pubsub_v1_generated_Publisher_ListTopicSubscriptions_async */ listTopicSubscriptionsAsync( request?: protos.google.pubsub.v1.IListTopicSubscriptionsRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -1351,11 +1566,14 @@ export class PublisherClient { }); const defaultCallSettings = this._defaults['listTopicSubscriptions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listTopicSubscriptions iterate %j', request); return this.descriptors.page.listTopicSubscriptions.asyncIterate( this.innerApiCalls['listTopicSubscriptions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -1390,7 +1608,7 @@ export class PublisherClient { */ listTopicSnapshots( request?: protos.google.pubsub.v1.IListTopicSnapshotsRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ string[], @@ -1405,7 +1623,7 @@ export class PublisherClient { protos.google.pubsub.v1.IListTopicSnapshotsRequest, protos.google.pubsub.v1.IListTopicSnapshotsResponse | null | undefined, string - > + >, ): void; listTopicSnapshots( request: protos.google.pubsub.v1.IListTopicSnapshotsRequest, @@ -1413,7 +1631,7 @@ export class PublisherClient { protos.google.pubsub.v1.IListTopicSnapshotsRequest, protos.google.pubsub.v1.IListTopicSnapshotsResponse | null | undefined, string - > + >, ): void; listTopicSnapshots( request?: protos.google.pubsub.v1.IListTopicSnapshotsRequest, @@ -1430,7 +1648,7 @@ export class PublisherClient { protos.google.pubsub.v1.IListTopicSnapshotsRequest, protos.google.pubsub.v1.IListTopicSnapshotsResponse | null | undefined, string - > + >, ): Promise< [ string[], @@ -1453,12 +1671,40 @@ export class PublisherClient { this._gaxModule.routingHeader.fromParams({ topic: request.topic ?? '', }); - this.initialize(); - return this.innerApiCalls.listTopicSnapshots(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListTopicSnapshotsRequest, + | protos.google.pubsub.v1.IListTopicSnapshotsResponse + | null + | undefined, + string + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listTopicSnapshots values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listTopicSnapshots request %j', request); + return this.innerApiCalls + .listTopicSnapshots(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + string[], + protos.google.pubsub.v1.IListTopicSnapshotsRequest | null, + protos.google.pubsub.v1.IListTopicSnapshotsResponse, + ]) => { + this._log.info('listTopicSnapshots values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listTopicSnapshots`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.topic @@ -1483,7 +1729,7 @@ export class PublisherClient { */ listTopicSnapshotsStream( request?: protos.google.pubsub.v1.IListTopicSnapshotsRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -1495,11 +1741,14 @@ export class PublisherClient { }); const defaultCallSettings = this._defaults['listTopicSnapshots']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listTopicSnapshots stream %j', request); return this.descriptors.page.listTopicSnapshots.createStream( this.innerApiCalls.listTopicSnapshots as GaxCall, request, - callSettings + callSettings, ); } @@ -1527,10 +1776,12 @@ export class PublisherClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/publisher.list_topic_snapshots.js + * region_tag:pubsub_v1_generated_Publisher_ListTopicSnapshots_async */ listTopicSnapshotsAsync( request?: protos.google.pubsub.v1.IListTopicSnapshotsRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -1542,11 +1793,14 @@ export class PublisherClient { }); const defaultCallSettings = this._defaults['listTopicSnapshots']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listTopicSnapshots iterate %j', request); return this.descriptors.page.listTopicSnapshots.asyncIterate( this.innerApiCalls['listTopicSnapshots'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -1587,7 +1841,7 @@ export class PublisherClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.getIamPolicy(request, options, callback); } @@ -1634,7 +1888,7 @@ export class PublisherClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } @@ -1682,7 +1936,7 @@ export class PublisherClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } @@ -1871,9 +2125,10 @@ export class PublisherClient { close(): Promise { if (this.publisherStub && !this._terminated) { return this.publisherStub.then(stub => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close(); + void this.iamClient.close(); }); } return Promise.resolve(); diff --git a/src/v1/schema_service_client.ts b/src/v1/schema_service_client.ts index d94d5a8e9..8ff7d2850 100644 --- a/src/v1/schema_service_client.ts +++ b/src/v1/schema_service_client.ts @@ -31,6 +31,7 @@ import type { import {Transform} from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging} from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -55,6 +56,8 @@ export class SchemaServiceClient { private _defaults: {[method: string]: gax.CallSettings}; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('pubsub'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -90,7 +93,7 @@ export class SchemaServiceClient { * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports - * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. @@ -109,7 +112,7 @@ export class SchemaServiceClient { */ constructor( opts?: ClientOptions, - gaxInstance?: typeof gax | typeof gax.fallback + gaxInstance?: typeof gax | typeof gax.fallback, ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SchemaServiceClient; @@ -119,7 +122,7 @@ export class SchemaServiceClient { opts?.universe_domain !== opts?.universeDomain ) { throw new Error( - 'Please set either universe_domain or universeDomain, but not both.' + 'Please set either universe_domain or universeDomain, but not both.', ); } const universeDomainEnvVar = @@ -144,9 +147,6 @@ export class SchemaServiceClient { (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); - // Request numeric enum values if REST transport is used. - opts.numericEnums = true; - // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; @@ -204,19 +204,19 @@ export class SchemaServiceClient { // Create useful helper objects for these. this.pathTemplates = { projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectTopicPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/topics/{topic}' + 'projects/{project}/topics/{topic}', ), schemaPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/schemas/{schema}' + 'projects/{project}/schemas/{schema}', ), snapshotPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/snapshots/{snapshot}' + 'projects/{project}/snapshots/{snapshot}', ), subscriptionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/subscriptions/{subscription}' + 'projects/{project}/subscriptions/{subscription}', ), }; @@ -227,12 +227,12 @@ export class SchemaServiceClient { listSchemas: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'schemas' + 'schemas', ), listSchemaRevisions: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'schemas' + 'schemas', ), }; @@ -241,7 +241,7 @@ export class SchemaServiceClient { 'google.pubsub.v1.SchemaService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -275,12 +275,12 @@ export class SchemaServiceClient { this.schemaServiceStub = this._gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( - 'google.pubsub.v1.SchemaService' + 'google.pubsub.v1.SchemaService', ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.pubsub.v1.SchemaService, this._opts, - this._providedCustomServicePath + this._providedCustomServicePath, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides @@ -309,7 +309,7 @@ export class SchemaServiceClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); const descriptor = this.descriptors.page[methodName] || undefined; @@ -317,7 +317,7 @@ export class SchemaServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -338,7 +338,7 @@ export class SchemaServiceClient { ) { process.emitWarning( 'Static servicePath is deprecated, please use the instance method instead.', - 'DeprecationWarning' + 'DeprecationWarning', ); } return 'pubsub.googleapis.com'; @@ -356,7 +356,7 @@ export class SchemaServiceClient { ) { process.emitWarning( 'Static apiEndpoint is deprecated, please use the instance method instead.', - 'DeprecationWarning' + 'DeprecationWarning', ); } return 'pubsub.googleapis.com'; @@ -401,7 +401,7 @@ export class SchemaServiceClient { * @returns {Promise} A promise that resolves to string containing the project ID. */ getProjectId( - callback?: Callback + callback?: Callback, ): Promise | void { if (callback) { this.auth.getProjectId(callback); @@ -439,10 +439,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Schema|Schema}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.create_schema.js + * region_tag:pubsub_v1_generated_SchemaService_CreateSchema_async */ createSchema( request?: protos.google.pubsub.v1.ICreateSchemaRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -457,7 +459,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.ICreateSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; createSchema( request: protos.google.pubsub.v1.ICreateSchemaRequest, @@ -465,7 +467,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.ICreateSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; createSchema( request?: protos.google.pubsub.v1.ICreateSchemaRequest, @@ -480,7 +482,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.ICreateSchemaRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -503,8 +505,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createSchema(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createSchema request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.ICreateSchemaRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createSchema response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.ICreateSchemaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSchema response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Gets a schema. @@ -523,10 +551,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Schema|Schema}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.get_schema.js + * region_tag:pubsub_v1_generated_SchemaService_GetSchema_async */ getSchema( request?: protos.google.pubsub.v1.IGetSchemaRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -541,7 +571,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IGetSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; getSchema( request: protos.google.pubsub.v1.IGetSchemaRequest, @@ -549,7 +579,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IGetSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; getSchema( request?: protos.google.pubsub.v1.IGetSchemaRequest, @@ -564,7 +594,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IGetSchemaRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -587,8 +617,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getSchema(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getSchema request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.IGetSchemaRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getSchema response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.IGetSchemaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSchema response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Commits a new schema revision to an existing schema. @@ -606,10 +662,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Schema|Schema}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.commit_schema.js + * region_tag:pubsub_v1_generated_SchemaService_CommitSchema_async */ commitSchema( request?: protos.google.pubsub.v1.ICommitSchemaRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -624,7 +682,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.ICommitSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; commitSchema( request: protos.google.pubsub.v1.ICommitSchemaRequest, @@ -632,7 +690,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.ICommitSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; commitSchema( request?: protos.google.pubsub.v1.ICommitSchemaRequest, @@ -647,7 +705,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.ICommitSchemaRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -670,8 +728,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.commitSchema(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('commitSchema request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.ICommitSchemaRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('commitSchema response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .commitSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.ICommitSchemaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('commitSchema response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Creates a new schema revision that is a copy of the provided revision_id. @@ -691,10 +775,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Schema|Schema}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.rollback_schema.js + * region_tag:pubsub_v1_generated_SchemaService_RollbackSchema_async */ rollbackSchema( request?: protos.google.pubsub.v1.IRollbackSchemaRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -709,7 +795,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IRollbackSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; rollbackSchema( request: protos.google.pubsub.v1.IRollbackSchemaRequest, @@ -717,7 +803,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IRollbackSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; rollbackSchema( request?: protos.google.pubsub.v1.IRollbackSchemaRequest, @@ -732,7 +818,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IRollbackSchemaRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -755,8 +841,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.rollbackSchema(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('rollbackSchema request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.IRollbackSchemaRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('rollbackSchema response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .rollbackSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.IRollbackSchemaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('rollbackSchema response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Deletes a specific schema revision. @@ -778,10 +890,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Schema|Schema}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.delete_schema_revision.js + * region_tag:pubsub_v1_generated_SchemaService_DeleteSchemaRevision_async */ deleteSchemaRevision( request?: protos.google.pubsub.v1.IDeleteSchemaRevisionRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -796,7 +910,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IDeleteSchemaRevisionRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSchemaRevision( request: protos.google.pubsub.v1.IDeleteSchemaRevisionRequest, @@ -804,7 +918,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IDeleteSchemaRevisionRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSchemaRevision( request?: protos.google.pubsub.v1.IDeleteSchemaRevisionRequest, @@ -821,7 +935,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.ISchema, protos.google.pubsub.v1.IDeleteSchemaRevisionRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema, @@ -844,8 +958,36 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteSchemaRevision(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteSchemaRevision request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISchema, + | protos.google.pubsub.v1.IDeleteSchemaRevisionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteSchemaRevision response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteSchemaRevision(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISchema, + protos.google.pubsub.v1.IDeleteSchemaRevisionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSchemaRevision response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Deletes a schema. @@ -861,10 +1003,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.delete_schema.js + * region_tag:pubsub_v1_generated_SchemaService_DeleteSchema_async */ deleteSchema( request?: protos.google.pubsub.v1.IDeleteSchemaRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -879,7 +1023,7 @@ export class SchemaServiceClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSchema( request: protos.google.pubsub.v1.IDeleteSchemaRequest, @@ -887,7 +1031,7 @@ export class SchemaServiceClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSchema( request?: protos.google.pubsub.v1.IDeleteSchemaRequest, @@ -902,7 +1046,7 @@ export class SchemaServiceClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSchemaRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -925,8 +1069,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteSchema(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteSchema request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteSchemaRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteSchema response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteSchemaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSchema response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Validates a schema. @@ -944,10 +1114,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.ValidateSchemaResponse|ValidateSchemaResponse}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.validate_schema.js + * region_tag:pubsub_v1_generated_SchemaService_ValidateSchema_async */ validateSchema( request?: protos.google.pubsub.v1.IValidateSchemaRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.IValidateSchemaResponse, @@ -962,7 +1134,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IValidateSchemaResponse, protos.google.pubsub.v1.IValidateSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; validateSchema( request: protos.google.pubsub.v1.IValidateSchemaRequest, @@ -970,7 +1142,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IValidateSchemaResponse, protos.google.pubsub.v1.IValidateSchemaRequest | null | undefined, {} | null | undefined - > + >, ): void; validateSchema( request?: protos.google.pubsub.v1.IValidateSchemaRequest, @@ -985,7 +1157,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IValidateSchemaResponse, protos.google.pubsub.v1.IValidateSchemaRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.IValidateSchemaResponse, @@ -1008,8 +1180,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.validateSchema(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('validateSchema request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.IValidateSchemaResponse, + protos.google.pubsub.v1.IValidateSchemaRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('validateSchema response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .validateSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.IValidateSchemaResponse, + protos.google.pubsub.v1.IValidateSchemaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('validateSchema response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Validates a message against a schema. @@ -1035,10 +1233,12 @@ export class SchemaServiceClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.ValidateMessageResponse|ValidateMessageResponse}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.validate_message.js + * region_tag:pubsub_v1_generated_SchemaService_ValidateMessage_async */ validateMessage( request?: protos.google.pubsub.v1.IValidateMessageRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.IValidateMessageResponse, @@ -1053,7 +1253,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IValidateMessageResponse, protos.google.pubsub.v1.IValidateMessageRequest | null | undefined, {} | null | undefined - > + >, ): void; validateMessage( request: protos.google.pubsub.v1.IValidateMessageRequest, @@ -1061,7 +1261,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IValidateMessageResponse, protos.google.pubsub.v1.IValidateMessageRequest | null | undefined, {} | null | undefined - > + >, ): void; validateMessage( request?: protos.google.pubsub.v1.IValidateMessageRequest, @@ -1076,7 +1276,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IValidateMessageResponse, protos.google.pubsub.v1.IValidateMessageRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.IValidateMessageResponse, @@ -1099,8 +1299,34 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.validateMessage(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('validateMessage request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.IValidateMessageResponse, + protos.google.pubsub.v1.IValidateMessageRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('validateMessage response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .validateMessage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.IValidateMessageResponse, + protos.google.pubsub.v1.IValidateMessageRequest | undefined, + {} | undefined, + ]) => { + this._log.info('validateMessage response %j', response); + return [response, options, rawResponse]; + }, + ); } /** @@ -1135,7 +1361,7 @@ export class SchemaServiceClient { */ listSchemas( request?: protos.google.pubsub.v1.IListSchemasRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema[], @@ -1150,7 +1376,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IListSchemasRequest, protos.google.pubsub.v1.IListSchemasResponse | null | undefined, protos.google.pubsub.v1.ISchema - > + >, ): void; listSchemas( request: protos.google.pubsub.v1.IListSchemasRequest, @@ -1158,7 +1384,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IListSchemasRequest, protos.google.pubsub.v1.IListSchemasResponse | null | undefined, protos.google.pubsub.v1.ISchema - > + >, ): void; listSchemas( request?: protos.google.pubsub.v1.IListSchemasRequest, @@ -1173,7 +1399,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IListSchemasRequest, protos.google.pubsub.v1.IListSchemasResponse | null | undefined, protos.google.pubsub.v1.ISchema - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema[], @@ -1196,12 +1422,38 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listSchemas(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListSchemasRequest, + protos.google.pubsub.v1.IListSchemasResponse | null | undefined, + protos.google.pubsub.v1.ISchema + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listSchemas values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listSchemas request %j', request); + return this.innerApiCalls + .listSchemas(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.pubsub.v1.ISchema[], + protos.google.pubsub.v1.IListSchemasRequest | null, + protos.google.pubsub.v1.IListSchemasResponse, + ]) => { + this._log.info('listSchemas values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listSchemas`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -1230,7 +1482,7 @@ export class SchemaServiceClient { */ listSchemasStream( request?: protos.google.pubsub.v1.IListSchemasRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -1242,11 +1494,14 @@ export class SchemaServiceClient { }); const defaultCallSettings = this._defaults['listSchemas']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSchemas stream %j', request); return this.descriptors.page.listSchemas.createStream( this.innerApiCalls.listSchemas as GaxCall, request, - callSettings + callSettings, ); } @@ -1278,10 +1533,12 @@ export class SchemaServiceClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.list_schemas.js + * region_tag:pubsub_v1_generated_SchemaService_ListSchemas_async */ listSchemasAsync( request?: protos.google.pubsub.v1.IListSchemasRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -1293,11 +1550,14 @@ export class SchemaServiceClient { }); const defaultCallSettings = this._defaults['listSchemas']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSchemas iterate %j', request); return this.descriptors.page.listSchemas.asyncIterate( this.innerApiCalls['listSchemas'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -1330,7 +1590,7 @@ export class SchemaServiceClient { */ listSchemaRevisions( request?: protos.google.pubsub.v1.IListSchemaRevisionsRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISchema[], @@ -1345,7 +1605,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IListSchemaRevisionsRequest, protos.google.pubsub.v1.IListSchemaRevisionsResponse | null | undefined, protos.google.pubsub.v1.ISchema - > + >, ): void; listSchemaRevisions( request: protos.google.pubsub.v1.IListSchemaRevisionsRequest, @@ -1353,7 +1613,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IListSchemaRevisionsRequest, protos.google.pubsub.v1.IListSchemaRevisionsResponse | null | undefined, protos.google.pubsub.v1.ISchema - > + >, ): void; listSchemaRevisions( request?: protos.google.pubsub.v1.IListSchemaRevisionsRequest, @@ -1370,7 +1630,7 @@ export class SchemaServiceClient { protos.google.pubsub.v1.IListSchemaRevisionsRequest, protos.google.pubsub.v1.IListSchemaRevisionsResponse | null | undefined, protos.google.pubsub.v1.ISchema - > + >, ): Promise< [ protos.google.pubsub.v1.ISchema[], @@ -1393,12 +1653,40 @@ export class SchemaServiceClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.listSchemaRevisions(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListSchemaRevisionsRequest, + | protos.google.pubsub.v1.IListSchemaRevisionsResponse + | null + | undefined, + protos.google.pubsub.v1.ISchema + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listSchemaRevisions values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listSchemaRevisions request %j', request); + return this.innerApiCalls + .listSchemaRevisions(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.pubsub.v1.ISchema[], + protos.google.pubsub.v1.IListSchemaRevisionsRequest | null, + protos.google.pubsub.v1.IListSchemaRevisionsResponse, + ]) => { + this._log.info('listSchemaRevisions values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listSchemaRevisions`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.name @@ -1425,7 +1713,7 @@ export class SchemaServiceClient { */ listSchemaRevisionsStream( request?: protos.google.pubsub.v1.IListSchemaRevisionsRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -1437,11 +1725,14 @@ export class SchemaServiceClient { }); const defaultCallSettings = this._defaults['listSchemaRevisions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSchemaRevisions stream %j', request); return this.descriptors.page.listSchemaRevisions.createStream( this.innerApiCalls.listSchemaRevisions as GaxCall, request, - callSettings + callSettings, ); } @@ -1471,10 +1762,12 @@ export class SchemaServiceClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/schema_service.list_schema_revisions.js + * region_tag:pubsub_v1_generated_SchemaService_ListSchemaRevisions_async */ listSchemaRevisionsAsync( request?: protos.google.pubsub.v1.IListSchemaRevisionsRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -1486,11 +1779,14 @@ export class SchemaServiceClient { }); const defaultCallSettings = this._defaults['listSchemaRevisions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSchemaRevisions iterate %j', request); return this.descriptors.page.listSchemaRevisions.asyncIterate( this.innerApiCalls['listSchemaRevisions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -1531,7 +1827,7 @@ export class SchemaServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.getIamPolicy(request, options, callback); } @@ -1578,7 +1874,7 @@ export class SchemaServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } @@ -1626,7 +1922,7 @@ export class SchemaServiceClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } @@ -1815,9 +2111,10 @@ export class SchemaServiceClient { close(): Promise { if (this.schemaServiceStub && !this._terminated) { return this.schemaServiceStub.then(stub => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close(); + void this.iamClient.close(); }); } return Promise.resolve(); diff --git a/src/v1/subscriber_client.ts b/src/v1/subscriber_client.ts index 26c6d9053..8113e2c15 100644 --- a/src/v1/subscriber_client.ts +++ b/src/v1/subscriber_client.ts @@ -31,6 +31,7 @@ import type { import {Transform, PassThrough} from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging} from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -57,6 +58,8 @@ export class SubscriberClient { private _defaults: {[method: string]: gax.CallSettings}; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('pubsub'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -92,7 +95,7 @@ export class SubscriberClient { * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports - * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. @@ -111,7 +114,7 @@ export class SubscriberClient { */ constructor( opts?: ClientOptions, - gaxInstance?: typeof gax | typeof gax.fallback + gaxInstance?: typeof gax | typeof gax.fallback, ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SubscriberClient; @@ -121,7 +124,7 @@ export class SubscriberClient { opts?.universe_domain !== opts?.universeDomain ) { throw new Error( - 'Please set either universe_domain or universeDomain, but not both.' + 'Please set either universe_domain or universeDomain, but not both.', ); } const universeDomainEnvVar = @@ -146,9 +149,6 @@ export class SubscriberClient { (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); - // Request numeric enum values if REST transport is used. - opts.numericEnums = true; - // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; @@ -206,19 +206,19 @@ export class SubscriberClient { // Create useful helper objects for these. this.pathTemplates = { projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectTopicPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/topics/{topic}' + 'projects/{project}/topics/{topic}', ), schemaPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/schemas/{schema}' + 'projects/{project}/schemas/{schema}', ), snapshotPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/snapshots/{snapshot}' + 'projects/{project}/snapshots/{snapshot}', ), subscriptionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/subscriptions/{subscription}' + 'projects/{project}/subscriptions/{subscription}', ), }; @@ -229,12 +229,12 @@ export class SubscriberClient { listSubscriptions: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'subscriptions' + 'subscriptions', ), listSnapshots: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', - 'snapshots' + 'snapshots', ), }; @@ -244,7 +244,7 @@ export class SubscriberClient { streamingPull: new this._gaxModule.StreamDescriptor( this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, - !!opts.gaxServerStreamingRetries + !!opts.gaxServerStreamingRetries, ), }; @@ -253,7 +253,7 @@ export class SubscriberClient { 'google.pubsub.v1.Subscriber', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -287,12 +287,12 @@ export class SubscriberClient { this.subscriberStub = this._gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( - 'google.pubsub.v1.Subscriber' + 'google.pubsub.v1.Subscriber', ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.pubsub.v1.Subscriber, this._opts, - this._providedCustomServicePath + this._providedCustomServicePath, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides @@ -321,13 +321,13 @@ export class SubscriberClient { (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough(); + const stream = new PassThrough({objectMode: true}); setImmediate(() => { stream.emit( 'error', new this._gaxModule.GoogleError( - 'The client has already been closed.' - ) + 'The client has already been closed.', + ), ); }); return stream; @@ -339,7 +339,7 @@ export class SubscriberClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); const descriptor = @@ -350,7 +350,7 @@ export class SubscriberClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -371,7 +371,7 @@ export class SubscriberClient { ) { process.emitWarning( 'Static servicePath is deprecated, please use the instance method instead.', - 'DeprecationWarning' + 'DeprecationWarning', ); } return 'pubsub.googleapis.com'; @@ -389,7 +389,7 @@ export class SubscriberClient { ) { process.emitWarning( 'Static apiEndpoint is deprecated, please use the instance method instead.', - 'DeprecationWarning' + 'DeprecationWarning', ); } return 'pubsub.googleapis.com'; @@ -434,7 +434,7 @@ export class SubscriberClient { * @returns {Promise} A promise that resolves to string containing the project ID. */ getProjectId( - callback?: Callback + callback?: Callback, ): Promise | void { if (callback) { this.auth.getProjectId(callback); @@ -586,16 +586,21 @@ export class SubscriberClient { * @param {google.pubsub.v1.Subscription.AnalyticsHubSubscriptionInfo} request.analyticsHubSubscriptionInfo * Output only. Information about the associated Analytics Hub subscription. * Only set if the subscritpion is created by Analytics Hub. + * @param {number[]} [request.messageTransforms] + * Optional. Transforms to be applied to messages before they are delivered to + * subscribers. Transforms are applied in the order specified. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing {@link protos.google.pubsub.v1.Subscription|Subscription}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.create_subscription.js + * region_tag:pubsub_v1_generated_Subscriber_CreateSubscription_async */ createSubscription( request?: protos.google.pubsub.v1.ISubscription, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISubscription, @@ -610,7 +615,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.ISubscription | null | undefined, {} | null | undefined - > + >, ): void; createSubscription( request: protos.google.pubsub.v1.ISubscription, @@ -618,7 +623,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.ISubscription | null | undefined, {} | null | undefined - > + >, ): void; createSubscription( request?: protos.google.pubsub.v1.ISubscription, @@ -633,7 +638,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.ISubscription | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISubscription, @@ -656,8 +661,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.createSubscription(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createSubscription request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISubscription, + protos.google.pubsub.v1.ISubscription | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createSubscription response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createSubscription(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISubscription, + protos.google.pubsub.v1.ISubscription | undefined, + {} | undefined, + ]) => { + this._log.info('createSubscription response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Gets the configuration details of a subscription. @@ -673,10 +704,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Subscription|Subscription}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.get_subscription.js + * region_tag:pubsub_v1_generated_Subscriber_GetSubscription_async */ getSubscription( request?: protos.google.pubsub.v1.IGetSubscriptionRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISubscription, @@ -691,7 +724,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.IGetSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; getSubscription( request: protos.google.pubsub.v1.IGetSubscriptionRequest, @@ -699,7 +732,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.IGetSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; getSubscription( request?: protos.google.pubsub.v1.IGetSubscriptionRequest, @@ -714,7 +747,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.IGetSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISubscription, @@ -737,8 +770,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.getSubscription(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getSubscription request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISubscription, + protos.google.pubsub.v1.IGetSubscriptionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getSubscription response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getSubscription(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISubscription, + protos.google.pubsub.v1.IGetSubscriptionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSubscription response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Updates an existing subscription by updating the fields specified in the @@ -758,10 +817,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Subscription|Subscription}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.update_subscription.js + * region_tag:pubsub_v1_generated_Subscriber_UpdateSubscription_async */ updateSubscription( request?: protos.google.pubsub.v1.IUpdateSubscriptionRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISubscription, @@ -776,7 +837,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.IUpdateSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; updateSubscription( request: protos.google.pubsub.v1.IUpdateSubscriptionRequest, @@ -784,7 +845,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.IUpdateSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; updateSubscription( request?: protos.google.pubsub.v1.IUpdateSubscriptionRequest, @@ -799,7 +860,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISubscription, protos.google.pubsub.v1.IUpdateSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISubscription, @@ -822,8 +883,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ 'subscription.name': request.subscription!.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateSubscription(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateSubscription request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISubscription, + protos.google.pubsub.v1.IUpdateSubscriptionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateSubscription response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateSubscription(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISubscription, + protos.google.pubsub.v1.IUpdateSubscriptionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSubscription response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Deletes an existing subscription. All messages retained in the subscription @@ -843,10 +930,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.delete_subscription.js + * region_tag:pubsub_v1_generated_Subscriber_DeleteSubscription_async */ deleteSubscription( request?: protos.google.pubsub.v1.IDeleteSubscriptionRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -861,7 +950,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSubscription( request: protos.google.pubsub.v1.IDeleteSubscriptionRequest, @@ -869,7 +958,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSubscription( request?: protos.google.pubsub.v1.IDeleteSubscriptionRequest, @@ -884,7 +973,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSubscriptionRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -907,8 +996,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteSubscription(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteSubscription request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteSubscriptionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteSubscription response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteSubscription(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteSubscriptionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSubscription response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Modifies the ack deadline for a specific message. This method is useful @@ -940,10 +1055,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.modify_ack_deadline.js + * region_tag:pubsub_v1_generated_Subscriber_ModifyAckDeadline_async */ modifyAckDeadline( request?: protos.google.pubsub.v1.IModifyAckDeadlineRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -958,7 +1075,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IModifyAckDeadlineRequest | null | undefined, {} | null | undefined - > + >, ): void; modifyAckDeadline( request: protos.google.pubsub.v1.IModifyAckDeadlineRequest, @@ -966,7 +1083,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IModifyAckDeadlineRequest | null | undefined, {} | null | undefined - > + >, ): void; modifyAckDeadline( request?: protos.google.pubsub.v1.IModifyAckDeadlineRequest, @@ -981,7 +1098,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IModifyAckDeadlineRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1004,8 +1121,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.modifyAckDeadline(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('modifyAckDeadline request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IModifyAckDeadlineRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('modifyAckDeadline response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .modifyAckDeadline(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IModifyAckDeadlineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('modifyAckDeadline response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Acknowledges the messages associated with the `ack_ids` in the @@ -1031,10 +1174,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.acknowledge.js + * region_tag:pubsub_v1_generated_Subscriber_Acknowledge_async */ acknowledge( request?: protos.google.pubsub.v1.IAcknowledgeRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1049,7 +1194,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IAcknowledgeRequest | null | undefined, {} | null | undefined - > + >, ): void; acknowledge( request: protos.google.pubsub.v1.IAcknowledgeRequest, @@ -1057,7 +1202,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IAcknowledgeRequest | null | undefined, {} | null | undefined - > + >, ): void; acknowledge( request?: protos.google.pubsub.v1.IAcknowledgeRequest, @@ -1072,7 +1217,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IAcknowledgeRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1095,8 +1240,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.acknowledge(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('acknowledge request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IAcknowledgeRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('acknowledge response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .acknowledge(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IAcknowledgeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('acknowledge response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Pulls messages from the server. @@ -1124,10 +1295,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.PullResponse|PullResponse}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.pull.js + * region_tag:pubsub_v1_generated_Subscriber_Pull_async */ pull( request?: protos.google.pubsub.v1.IPullRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.IPullResponse, @@ -1142,7 +1315,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IPullResponse, protos.google.pubsub.v1.IPullRequest | null | undefined, {} | null | undefined - > + >, ): void; pull( request: protos.google.pubsub.v1.IPullRequest, @@ -1150,7 +1323,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IPullResponse, protos.google.pubsub.v1.IPullRequest | null | undefined, {} | null | undefined - > + >, ): void; pull( request?: protos.google.pubsub.v1.IPullRequest, @@ -1165,7 +1338,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IPullResponse, protos.google.pubsub.v1.IPullRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.IPullResponse, @@ -1188,8 +1361,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.pull(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('pull request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.IPullResponse, + protos.google.pubsub.v1.IPullRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('pull response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .pull(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.IPullResponse, + protos.google.pubsub.v1.IPullRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pull response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Modifies the `PushConfig` for a specified subscription. @@ -1217,10 +1416,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.modify_push_config.js + * region_tag:pubsub_v1_generated_Subscriber_ModifyPushConfig_async */ modifyPushConfig( request?: protos.google.pubsub.v1.IModifyPushConfigRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1235,7 +1436,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IModifyPushConfigRequest | null | undefined, {} | null | undefined - > + >, ): void; modifyPushConfig( request: protos.google.pubsub.v1.IModifyPushConfigRequest, @@ -1243,7 +1444,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IModifyPushConfigRequest | null | undefined, {} | null | undefined - > + >, ): void; modifyPushConfig( request?: protos.google.pubsub.v1.IModifyPushConfigRequest, @@ -1258,7 +1459,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IModifyPushConfigRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1281,8 +1482,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.modifyPushConfig(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('modifyPushConfig request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IModifyPushConfigRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('modifyPushConfig response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .modifyPushConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IModifyPushConfigRequest | undefined, + {} | undefined, + ]) => { + this._log.info('modifyPushConfig response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Gets the configuration details of a snapshot. Snapshots are used in @@ -1302,10 +1529,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Snapshot|Snapshot}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.get_snapshot.js + * region_tag:pubsub_v1_generated_Subscriber_GetSnapshot_async */ getSnapshot( request?: protos.google.pubsub.v1.IGetSnapshotRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISnapshot, @@ -1320,7 +1549,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.IGetSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; getSnapshot( request: protos.google.pubsub.v1.IGetSnapshotRequest, @@ -1328,7 +1557,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.IGetSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; getSnapshot( request?: protos.google.pubsub.v1.IGetSnapshotRequest, @@ -1343,7 +1572,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.IGetSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISnapshot, @@ -1366,8 +1595,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ snapshot: request.snapshot ?? '', }); - this.initialize(); - return this.innerApiCalls.getSnapshot(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getSnapshot request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISnapshot, + protos.google.pubsub.v1.IGetSnapshotRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getSnapshot response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getSnapshot(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISnapshot, + protos.google.pubsub.v1.IGetSnapshotRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSnapshot response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Creates a snapshot from the requested subscription. Snapshots are used in @@ -1415,10 +1670,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Snapshot|Snapshot}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.create_snapshot.js + * region_tag:pubsub_v1_generated_Subscriber_CreateSnapshot_async */ createSnapshot( request?: protos.google.pubsub.v1.ICreateSnapshotRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISnapshot, @@ -1433,7 +1690,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.ICreateSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; createSnapshot( request: protos.google.pubsub.v1.ICreateSnapshotRequest, @@ -1441,7 +1698,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.ICreateSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; createSnapshot( request?: protos.google.pubsub.v1.ICreateSnapshotRequest, @@ -1456,7 +1713,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.ICreateSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISnapshot, @@ -1479,8 +1736,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.createSnapshot(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createSnapshot request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISnapshot, + protos.google.pubsub.v1.ICreateSnapshotRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createSnapshot response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createSnapshot(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISnapshot, + protos.google.pubsub.v1.ICreateSnapshotRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSnapshot response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Updates an existing snapshot by updating the fields specified in the update @@ -1503,10 +1786,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.Snapshot|Snapshot}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.update_snapshot.js + * region_tag:pubsub_v1_generated_Subscriber_UpdateSnapshot_async */ updateSnapshot( request?: protos.google.pubsub.v1.IUpdateSnapshotRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISnapshot, @@ -1521,7 +1806,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.IUpdateSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; updateSnapshot( request: protos.google.pubsub.v1.IUpdateSnapshotRequest, @@ -1529,7 +1814,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.IUpdateSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; updateSnapshot( request?: protos.google.pubsub.v1.IUpdateSnapshotRequest, @@ -1544,7 +1829,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISnapshot, protos.google.pubsub.v1.IUpdateSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISnapshot, @@ -1567,8 +1852,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ 'snapshot.name': request.snapshot!.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateSnapshot(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateSnapshot request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISnapshot, + protos.google.pubsub.v1.IUpdateSnapshotRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateSnapshot response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateSnapshot(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISnapshot, + protos.google.pubsub.v1.IUpdateSnapshotRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSnapshot response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Removes an existing snapshot. Snapshots are used in [Seek] @@ -1592,10 +1903,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.delete_snapshot.js + * region_tag:pubsub_v1_generated_Subscriber_DeleteSnapshot_async */ deleteSnapshot( request?: protos.google.pubsub.v1.IDeleteSnapshotRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1610,7 +1923,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSnapshot( request: protos.google.pubsub.v1.IDeleteSnapshotRequest, @@ -1618,7 +1931,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): void; deleteSnapshot( request?: protos.google.pubsub.v1.IDeleteSnapshotRequest, @@ -1633,7 +1946,7 @@ export class SubscriberClient { protos.google.protobuf.IEmpty, protos.google.pubsub.v1.IDeleteSnapshotRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.protobuf.IEmpty, @@ -1656,8 +1969,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ snapshot: request.snapshot ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteSnapshot(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteSnapshot request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteSnapshotRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteSnapshot response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteSnapshot(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.pubsub.v1.IDeleteSnapshotRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSnapshot response %j', response); + return [response, options, rawResponse]; + }, + ); } /** * Seeks an existing subscription to a point in time or to a given snapshot, @@ -1694,10 +2033,12 @@ export class SubscriberClient { * The first element of the array is an object representing {@link protos.google.pubsub.v1.SeekResponse|SeekResponse}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.seek.js + * region_tag:pubsub_v1_generated_Subscriber_Seek_async */ seek( request?: protos.google.pubsub.v1.ISeekRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISeekResponse, @@ -1712,7 +2053,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISeekResponse, protos.google.pubsub.v1.ISeekRequest | null | undefined, {} | null | undefined - > + >, ): void; seek( request: protos.google.pubsub.v1.ISeekRequest, @@ -1720,7 +2061,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISeekResponse, protos.google.pubsub.v1.ISeekRequest | null | undefined, {} | null | undefined - > + >, ): void; seek( request?: protos.google.pubsub.v1.ISeekRequest, @@ -1735,7 +2076,7 @@ export class SubscriberClient { protos.google.pubsub.v1.ISeekResponse, protos.google.pubsub.v1.ISeekRequest | null | undefined, {} | null | undefined - > + >, ): Promise< [ protos.google.pubsub.v1.ISeekResponse, @@ -1758,8 +2099,34 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ subscription: request.subscription ?? '', }); - this.initialize(); - return this.innerApiCalls.seek(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + this._log.info('seek request %j', request); + const wrappedCallback: + | Callback< + protos.google.pubsub.v1.ISeekResponse, + protos.google.pubsub.v1.ISeekRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('seek response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .seek(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.pubsub.v1.ISeekResponse, + protos.google.pubsub.v1.ISeekRequest | undefined, + {} | undefined, + ]) => { + this._log.info('seek response %j', response); + return [response, options, rawResponse]; + }, + ); } /** @@ -1779,9 +2146,14 @@ export class SubscriberClient { * will emit objects representing {@link protos.google.pubsub.v1.StreamingPullResponse|StreamingPullResponse} on 'data' event asynchronously. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.streaming_pull.js + * region_tag:pubsub_v1_generated_Subscriber_StreamingPull_async */ streamingPull(options?: CallOptions): gax.CancellableStream { - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('streamingPull stream %j', options); return this.innerApiCalls.streamingPull(null, options); } @@ -1813,7 +2185,7 @@ export class SubscriberClient { */ listSubscriptions( request?: protos.google.pubsub.v1.IListSubscriptionsRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISubscription[], @@ -1828,7 +2200,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IListSubscriptionsRequest, protos.google.pubsub.v1.IListSubscriptionsResponse | null | undefined, protos.google.pubsub.v1.ISubscription - > + >, ): void; listSubscriptions( request: protos.google.pubsub.v1.IListSubscriptionsRequest, @@ -1836,7 +2208,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IListSubscriptionsRequest, protos.google.pubsub.v1.IListSubscriptionsResponse | null | undefined, protos.google.pubsub.v1.ISubscription - > + >, ): void; listSubscriptions( request?: protos.google.pubsub.v1.IListSubscriptionsRequest, @@ -1851,7 +2223,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IListSubscriptionsRequest, protos.google.pubsub.v1.IListSubscriptionsResponse | null | undefined, protos.google.pubsub.v1.ISubscription - > + >, ): Promise< [ protos.google.pubsub.v1.ISubscription[], @@ -1874,12 +2246,38 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ project: request.project ?? '', }); - this.initialize(); - return this.innerApiCalls.listSubscriptions(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListSubscriptionsRequest, + protos.google.pubsub.v1.IListSubscriptionsResponse | null | undefined, + protos.google.pubsub.v1.ISubscription + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listSubscriptions values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listSubscriptions request %j', request); + return this.innerApiCalls + .listSubscriptions(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.pubsub.v1.ISubscription[], + protos.google.pubsub.v1.IListSubscriptionsRequest | null, + protos.google.pubsub.v1.IListSubscriptionsResponse, + ]) => { + this._log.info('listSubscriptions values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listSubscriptions`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.project @@ -1904,7 +2302,7 @@ export class SubscriberClient { */ listSubscriptionsStream( request?: protos.google.pubsub.v1.IListSubscriptionsRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -1916,11 +2314,14 @@ export class SubscriberClient { }); const defaultCallSettings = this._defaults['listSubscriptions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSubscriptions stream %j', request); return this.descriptors.page.listSubscriptions.createStream( this.innerApiCalls.listSubscriptions as GaxCall, request, - callSettings + callSettings, ); } @@ -1948,10 +2349,12 @@ export class SubscriberClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.list_subscriptions.js + * region_tag:pubsub_v1_generated_Subscriber_ListSubscriptions_async */ listSubscriptionsAsync( request?: protos.google.pubsub.v1.IListSubscriptionsRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -1963,11 +2366,14 @@ export class SubscriberClient { }); const defaultCallSettings = this._defaults['listSubscriptions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSubscriptions iterate %j', request); return this.descriptors.page.listSubscriptions.asyncIterate( this.innerApiCalls['listSubscriptions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -2002,7 +2408,7 @@ export class SubscriberClient { */ listSnapshots( request?: protos.google.pubsub.v1.IListSnapshotsRequest, - options?: CallOptions + options?: CallOptions, ): Promise< [ protos.google.pubsub.v1.ISnapshot[], @@ -2017,7 +2423,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IListSnapshotsRequest, protos.google.pubsub.v1.IListSnapshotsResponse | null | undefined, protos.google.pubsub.v1.ISnapshot - > + >, ): void; listSnapshots( request: protos.google.pubsub.v1.IListSnapshotsRequest, @@ -2025,7 +2431,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IListSnapshotsRequest, protos.google.pubsub.v1.IListSnapshotsResponse | null | undefined, protos.google.pubsub.v1.ISnapshot - > + >, ): void; listSnapshots( request?: protos.google.pubsub.v1.IListSnapshotsRequest, @@ -2040,7 +2446,7 @@ export class SubscriberClient { protos.google.pubsub.v1.IListSnapshotsRequest, protos.google.pubsub.v1.IListSnapshotsResponse | null | undefined, protos.google.pubsub.v1.ISnapshot - > + >, ): Promise< [ protos.google.pubsub.v1.ISnapshot[], @@ -2063,12 +2469,38 @@ export class SubscriberClient { this._gaxModule.routingHeader.fromParams({ project: request.project ?? '', }); - this.initialize(); - return this.innerApiCalls.listSnapshots(request, options, callback); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.pubsub.v1.IListSnapshotsRequest, + protos.google.pubsub.v1.IListSnapshotsResponse | null | undefined, + protos.google.pubsub.v1.ISnapshot + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listSnapshots values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listSnapshots request %j', request); + return this.innerApiCalls + .listSnapshots(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.pubsub.v1.ISnapshot[], + protos.google.pubsub.v1.IListSnapshotsRequest | null, + protos.google.pubsub.v1.IListSnapshotsResponse, + ]) => { + this._log.info('listSnapshots values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listSnapshots`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.project @@ -2093,7 +2525,7 @@ export class SubscriberClient { */ listSnapshotsStream( request?: protos.google.pubsub.v1.IListSnapshotsRequest, - options?: CallOptions + options?: CallOptions, ): Transform { request = request || {}; options = options || {}; @@ -2105,11 +2537,14 @@ export class SubscriberClient { }); const defaultCallSettings = this._defaults['listSnapshots']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSnapshots stream %j', request); return this.descriptors.page.listSnapshots.createStream( this.innerApiCalls.listSnapshots as GaxCall, request, - callSettings + callSettings, ); } @@ -2137,10 +2572,12 @@ export class SubscriberClient { * so you can stop the iteration when you don't need more results. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. + * @example include:samples/generated/v1/subscriber.list_snapshots.js + * region_tag:pubsub_v1_generated_Subscriber_ListSnapshots_async */ listSnapshotsAsync( request?: protos.google.pubsub.v1.IListSnapshotsRequest, - options?: CallOptions + options?: CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -2152,11 +2589,14 @@ export class SubscriberClient { }); const defaultCallSettings = this._defaults['listSnapshots']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSnapshots iterate %j', request); return this.descriptors.page.listSnapshots.asyncIterate( this.innerApiCalls['listSnapshots'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } /** @@ -2197,7 +2637,7 @@ export class SubscriberClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.getIamPolicy(request, options, callback); } @@ -2244,7 +2684,7 @@ export class SubscriberClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } @@ -2292,7 +2732,7 @@ export class SubscriberClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } @@ -2481,9 +2921,10 @@ export class SubscriberClient { close(): Promise { if (this.subscriberStub && !this._terminated) { return this.subscriberStub.then(stub => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close(); + void this.iamClient.close(); }); } return Promise.resolve(); diff --git a/system-test/pubsub.ts b/system-test/pubsub.ts index ca152fda7..82bff2aa3 100644 --- a/system-test/pubsub.ts +++ b/system-test/pubsub.ts @@ -31,6 +31,7 @@ import { SchemaTypes, SchemaViews, ISchema, + Duration, } from '../src'; import {Policy, IamPermissionsMap} from '../src/iam'; import {MessageOptions} from '../src/topic'; @@ -428,10 +429,12 @@ describe('pubsub', () => { const SUB_NAMES = [generateSubName(), generateSubName()]; const SUB_DETACH_NAME = generateSubForDetach(); + const thirty = Duration.from({minutes: 30}); + const sixty = Duration.from({minutes: 60}); const SUBSCRIPTIONS = [ - topic.subscription(SUB_NAMES[0], {ackDeadline: 30}), - topic.subscription(SUB_NAMES[1], {ackDeadline: 60}), - topic.subscription(SUB_DETACH_NAME, {ackDeadline: 30}), + topic.subscription(SUB_NAMES[0], {minAckDeadline: thirty, maxAckDeadline: thirty}), + topic.subscription(SUB_NAMES[1], {minAckDeadline: sixty, maxAckDeadline: sixty}), + topic.subscription(SUB_DETACH_NAME, {minAckDeadline: thirty, maxAckDeadline: thirty}), ]; before(async () => { diff --git a/test/exponential-retry.ts b/test/exponential-retry.ts index f96689165..50834032a 100644 --- a/test/exponential-retry.ts +++ b/test/exponential-retry.ts @@ -18,6 +18,7 @@ import * as sinon from 'sinon'; import {ExponentialRetry} from '../src/exponential-retry'; import {Duration} from '../src/temporal'; +import {TestUtils} from './test-utils'; // eslint-disable-next-line @typescript-eslint/no-explicit-any function introspect(obj: unknown): any { @@ -43,7 +44,7 @@ describe('exponential retry class', () => { // class is storing the durations as numbers internally. const er = new ExponentialRetry( Duration.from({seconds: 1}), - Duration.from({seconds: 2}) + Duration.from({seconds: 2}), ); const eri = introspect(er); @@ -52,30 +53,33 @@ describe('exponential retry class', () => { }); it('makes the first callback', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const er = new ExponentialRetry( Duration.from({millis: 100}), - Duration.from({millis: 1000}) + Duration.from({millis: 1000}), ); sandbox.stub(global.Math, 'random').returns(0.75); const item = makeItem(); + let retried = false; er.retryLater(item, (s: typeof item, t: Duration) => { assert.strictEqual(s, item); assert.strictEqual(t.totalOf('millisecond'), 125); + retried = true; }); clock.tick(125); const leftovers = er.close(); + assert.strictEqual(retried, true); assert.strictEqual(leftovers.length, 0); }); it('closes gracefully', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const er = new ExponentialRetry( Duration.from({millis: 100}), - Duration.from({millis: 1000}) + Duration.from({millis: 1000}), ); sandbox.stub(global.Math, 'random').returns(0.75); @@ -102,10 +106,10 @@ describe('exponential retry class', () => { }); it('backs off exponentially', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const er = new ExponentialRetry( Duration.from({millis: 100}), - Duration.from({millis: 1000}) + Duration.from({millis: 1000}), ); sandbox.stub(global.Math, 'random').returns(0.75); @@ -136,11 +140,11 @@ describe('exponential retry class', () => { }); it('backs off exponentially until the max backoff', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const item = makeItem(); const er = new ExponentialRetry( Duration.from({millis: 100}), - Duration.from({millis: 150}) + Duration.from({millis: 150}), ); sandbox.stub(global.Math, 'random').returns(0.75); @@ -170,12 +174,12 @@ describe('exponential retry class', () => { }); it('calls retries in the right order', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const items = [makeItem(), makeItem()]; const er = new ExponentialRetry( Duration.from({millis: 100}), - Duration.from({millis: 1000}) + Duration.from({millis: 1000}), ); // Just disable the fuzz for this test. @@ -204,7 +208,7 @@ describe('exponential retry class', () => { assert.deepStrictEqual(callbackCounts, [2, 0]); assert.deepStrictEqual( callbackTimes.map(d => d.totalOf('millisecond')), - [300, 0] + [300, 0], ); // Load in the second item and get it retrying. @@ -217,7 +221,7 @@ describe('exponential retry class', () => { assert.deepStrictEqual(callbackCounts, [2, 1]); assert.deepStrictEqual( callbackTimes.map(d => d.totalOf('millisecond')), - [300, 100] + [300, 100], ); // Make sure that we did in fact set another timer for the next event. diff --git a/test/gapic_publisher_v1.ts b/test/gapic_publisher_v1.ts index 07023b4cd..419f99cc5 100644 --- a/test/gapic_publisher_v1.ts +++ b/test/gapic_publisher_v1.ts @@ -30,7 +30,7 @@ import {protobuf, IamProtos} from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects const root = protobuf.Root.fromJSON( - require('../protos/protos.json') + require('../protos/protos.json'), ).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -47,7 +47,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -59,7 +59,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -68,7 +68,7 @@ function stubSimpleCallWithCallback( function stubPageStreamingCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { const pagingStub = sinon.stub(); if (responses) { @@ -106,7 +106,7 @@ function stubPageStreamingCall( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -250,9 +250,11 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(err => { + throw err; + }); assert(client.publisherStub); - client.close().then(() => { + void client.close().then(() => { done(); }); }); @@ -263,7 +265,7 @@ describe('v1.PublisherClient', () => { projectId: 'bogus', }); assert.strictEqual(client.publisherStub, undefined); - client.close().then(() => { + void client.close().then(() => { done(); }); }); @@ -309,17 +311,17 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); const defaultValue1 = getTypeDefaultValue('.google.pubsub.v1.Topic', [ 'name', ]); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); client.innerApiCalls.createTopic = stubSimpleCall(expectedResponse); const [response] = await client.createTopic(request); @@ -339,17 +341,17 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); const defaultValue1 = getTypeDefaultValue('.google.pubsub.v1.Topic', [ 'name', ]); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); client.innerApiCalls.createTopic = stubSimpleCallWithCallback(expectedResponse); @@ -358,14 +360,14 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ITopic | null + result?: protos.google.pubsub.v1.ITopic | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -385,19 +387,19 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); const defaultValue1 = getTypeDefaultValue('.google.pubsub.v1.Topic', [ 'name', ]); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createTopic = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.createTopic(request), expectedError); const actualRequest = ( @@ -415,16 +417,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); const defaultValue1 = getTypeDefaultValue('.google.pubsub.v1.Topic', [ 'name', ]); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.createTopic(request), expectedError); }); }); @@ -435,19 +437,19 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateTopicRequest() + new protos.google.pubsub.v1.UpdateTopicRequest(), ); request.topic ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateTopicRequest', - ['topic', 'name'] + ['topic', 'name'], ); request.topic.name = defaultValue1; - const expectedHeaderRequestParams = `topic.name=${defaultValue1}`; + const expectedHeaderRequestParams = `topic.name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); client.innerApiCalls.updateTopic = stubSimpleCall(expectedResponse); const [response] = await client.updateTopic(request); @@ -467,19 +469,19 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateTopicRequest() + new protos.google.pubsub.v1.UpdateTopicRequest(), ); request.topic ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateTopicRequest', - ['topic', 'name'] + ['topic', 'name'], ); request.topic.name = defaultValue1; - const expectedHeaderRequestParams = `topic.name=${defaultValue1}`; + const expectedHeaderRequestParams = `topic.name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); client.innerApiCalls.updateTopic = stubSimpleCallWithCallback(expectedResponse); @@ -488,14 +490,14 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ITopic | null + result?: protos.google.pubsub.v1.ITopic | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -515,21 +517,21 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateTopicRequest() + new protos.google.pubsub.v1.UpdateTopicRequest(), ); request.topic ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateTopicRequest', - ['topic', 'name'] + ['topic', 'name'], ); request.topic.name = defaultValue1; - const expectedHeaderRequestParams = `topic.name=${defaultValue1}`; + const expectedHeaderRequestParams = `topic.name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateTopic = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.updateTopic(request), expectedError); const actualRequest = ( @@ -547,18 +549,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateTopicRequest() + new protos.google.pubsub.v1.UpdateTopicRequest(), ); request.topic ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateTopicRequest', - ['topic', 'name'] + ['topic', 'name'], ); request.topic.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.updateTopic(request), expectedError); }); }); @@ -569,24 +571,24 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PublishRequest() + new protos.google.pubsub.v1.PublishRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PublishRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.PublishResponse() + new protos.google.pubsub.v1.PublishResponse(), ); client.innerApiCalls.publish = stubSimpleCall(expectedResponse); const [response] = await client.publish(request); assert.deepStrictEqual(response, expectedResponse); const actualRequest = (client.innerApiCalls.publish as SinonStub).getCall( - 0 + 0, ).args[0]; assert.deepStrictEqual(actualRequest, request); const actualHeaderRequestParams = ( @@ -600,18 +602,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PublishRequest() + new protos.google.pubsub.v1.PublishRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PublishRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.PublishResponse() + new protos.google.pubsub.v1.PublishResponse(), ); client.innerApiCalls.publish = stubSimpleCallWithCallback(expectedResponse); @@ -620,20 +622,20 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.IPublishResponse | null + result?: protos.google.pubsub.v1.IPublishResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); const actualRequest = (client.innerApiCalls.publish as SinonStub).getCall( - 0 + 0, ).args[0]; assert.deepStrictEqual(actualRequest, request); const actualHeaderRequestParams = ( @@ -647,21 +649,21 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PublishRequest() + new protos.google.pubsub.v1.PublishRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PublishRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.publish = stubSimpleCall(undefined, expectedError); await assert.rejects(client.publish(request), expectedError); const actualRequest = (client.innerApiCalls.publish as SinonStub).getCall( - 0 + 0, ).args[0]; assert.deepStrictEqual(actualRequest, request); const actualHeaderRequestParams = ( @@ -675,17 +677,17 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PublishRequest() + new protos.google.pubsub.v1.PublishRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PublishRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.publish(request), expectedError); }); }); @@ -696,18 +698,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetTopicRequest() + new protos.google.pubsub.v1.GetTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); client.innerApiCalls.getTopic = stubSimpleCall(expectedResponse); const [response] = await client.getTopic(request); @@ -727,18 +729,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetTopicRequest() + new protos.google.pubsub.v1.GetTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Topic() + new protos.google.pubsub.v1.Topic(), ); client.innerApiCalls.getTopic = stubSimpleCallWithCallback(expectedResponse); @@ -747,14 +749,14 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ITopic | null + result?: protos.google.pubsub.v1.ITopic | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -774,16 +776,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetTopicRequest() + new protos.google.pubsub.v1.GetTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getTopic = stubSimpleCall(undefined, expectedError); await assert.rejects(client.getTopic(request), expectedError); @@ -802,17 +804,17 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetTopicRequest() + new protos.google.pubsub.v1.GetTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.getTopic(request), expectedError); }); }); @@ -823,18 +825,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteTopicRequest() + new protos.google.pubsub.v1.DeleteTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteTopic = stubSimpleCall(expectedResponse); const [response] = await client.deleteTopic(request); @@ -854,18 +856,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteTopicRequest() + new protos.google.pubsub.v1.DeleteTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteTopic = stubSimpleCallWithCallback(expectedResponse); @@ -874,14 +876,14 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -901,20 +903,20 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteTopicRequest() + new protos.google.pubsub.v1.DeleteTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteTopic = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.deleteTopic(request), expectedError); const actualRequest = ( @@ -932,17 +934,17 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteTopicRequest() + new protos.google.pubsub.v1.DeleteTopicRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteTopicRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.deleteTopic(request), expectedError); }); }); @@ -953,18 +955,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DetachSubscriptionRequest() + new protos.google.pubsub.v1.DetachSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DetachSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.DetachSubscriptionResponse() + new protos.google.pubsub.v1.DetachSubscriptionResponse(), ); client.innerApiCalls.detachSubscription = stubSimpleCall(expectedResponse); @@ -985,18 +987,18 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DetachSubscriptionRequest() + new protos.google.pubsub.v1.DetachSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DetachSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.DetachSubscriptionResponse() + new protos.google.pubsub.v1.DetachSubscriptionResponse(), ); client.innerApiCalls.detachSubscription = stubSimpleCallWithCallback(expectedResponse); @@ -1005,14 +1007,14 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.IDetachSubscriptionResponse | null + result?: protos.google.pubsub.v1.IDetachSubscriptionResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1032,20 +1034,20 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DetachSubscriptionRequest() + new protos.google.pubsub.v1.DetachSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DetachSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.detachSubscription = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.detachSubscription(request), expectedError); const actualRequest = ( @@ -1063,17 +1065,17 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DetachSubscriptionRequest() + new protos.google.pubsub.v1.DetachSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DetachSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.detachSubscription(request), expectedError); }); }); @@ -1084,16 +1086,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Topic()), generateSampleMessage(new protos.google.pubsub.v1.Topic()), @@ -1117,16 +1119,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Topic()), generateSampleMessage(new protos.google.pubsub.v1.Topic()), @@ -1139,14 +1141,14 @@ describe('v1.PublisherClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ITopic[] | null + result?: protos.google.pubsub.v1.ITopic[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1166,20 +1168,20 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listTopics = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.listTopics(request), expectedError); const actualRequest = ( @@ -1197,16 +1199,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Topic()), generateSampleMessage(new protos.google.pubsub.v1.Topic()), @@ -1232,14 +1234,14 @@ describe('v1.PublisherClient', () => { assert( (client.descriptors.page.listTopics.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listTopics, request) + .calledWith(client.innerApiCalls.listTopics, request), ); assert( (client.descriptors.page.listTopics.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1248,20 +1250,20 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listTopics.createStream = stubPageStreamingCall( undefined, - expectedError + expectedError, ); const stream = client.listTopicsStream(request); const promise = new Promise((resolve, reject) => { @@ -1280,14 +1282,14 @@ describe('v1.PublisherClient', () => { assert( (client.descriptors.page.listTopics.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listTopics, request) + .calledWith(client.innerApiCalls.listTopics, request), ); assert( (client.descriptors.page.listTopics.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1296,16 +1298,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Topic()), generateSampleMessage(new protos.google.pubsub.v1.Topic()), @@ -1321,16 +1323,16 @@ describe('v1.PublisherClient', () => { assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( (client.descriptors.page.listTopics.asyncIterate as SinonStub).getCall( - 0 + 0, ).args[1], - request + request, ); assert( (client.descriptors.page.listTopics.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1339,20 +1341,20 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicsRequest() + new protos.google.pubsub.v1.ListTopicsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listTopics.asyncIterate = stubAsyncIterationCall( undefined, - expectedError + expectedError, ); const iterable = client.listTopicsAsync(request); await assert.rejects(async () => { @@ -1363,16 +1365,16 @@ describe('v1.PublisherClient', () => { }); assert.deepStrictEqual( (client.descriptors.page.listTopics.asyncIterate as SinonStub).getCall( - 0 + 0, ).args[1], - request + request, ); assert( (client.descriptors.page.listTopics.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); }); @@ -1383,16 +1385,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.innerApiCalls.listTopicSubscriptions = stubSimpleCall(expectedResponse); @@ -1413,16 +1415,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.innerApiCalls.listTopicSubscriptions = stubSimpleCallWithCallback(expectedResponse); @@ -1435,7 +1437,7 @@ describe('v1.PublisherClient', () => { } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1455,24 +1457,24 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listTopicSubscriptions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.listTopicSubscriptions(request), - expectedError + expectedError, ); const actualRequest = ( client.innerApiCalls.listTopicSubscriptions as SinonStub @@ -1489,16 +1491,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.descriptors.page.listTopicSubscriptions.createStream = stubPageStreamingCall(expectedResponse); @@ -1523,7 +1525,7 @@ describe('v1.PublisherClient', () => { .createStream as SinonStub ) .getCall(0) - .calledWith(client.innerApiCalls.listTopicSubscriptions, request) + .calledWith(client.innerApiCalls.listTopicSubscriptions, request), ); assert( ( @@ -1532,8 +1534,8 @@ describe('v1.PublisherClient', () => { ) .getCall(0) .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + expectedHeaderRequestParams, + ), ); }); @@ -1542,16 +1544,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listTopicSubscriptions.createStream = stubPageStreamingCall(undefined, expectedError); @@ -1575,7 +1577,7 @@ describe('v1.PublisherClient', () => { .createStream as SinonStub ) .getCall(0) - .calledWith(client.innerApiCalls.listTopicSubscriptions, request) + .calledWith(client.innerApiCalls.listTopicSubscriptions, request), ); assert( ( @@ -1584,8 +1586,8 @@ describe('v1.PublisherClient', () => { ) .getCall(0) .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + expectedHeaderRequestParams, + ), ); }); @@ -1594,16 +1596,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.descriptors.page.listTopicSubscriptions.asyncIterate = stubAsyncIterationCall(expectedResponse); @@ -1618,7 +1620,7 @@ describe('v1.PublisherClient', () => { client.descriptors.page.listTopicSubscriptions .asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( ( @@ -1627,8 +1629,8 @@ describe('v1.PublisherClient', () => { ) .getCall(0) .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + expectedHeaderRequestParams, + ), ); }); @@ -1637,16 +1639,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSubscriptionsRequest() + new protos.google.pubsub.v1.ListTopicSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSubscriptionsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listTopicSubscriptions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -1662,7 +1664,7 @@ describe('v1.PublisherClient', () => { client.descriptors.page.listTopicSubscriptions .asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( ( @@ -1671,8 +1673,8 @@ describe('v1.PublisherClient', () => { ) .getCall(0) .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + expectedHeaderRequestParams, + ), ); }); }); @@ -1683,16 +1685,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.innerApiCalls.listTopicSnapshots = stubSimpleCall(expectedResponse); @@ -1713,16 +1715,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.innerApiCalls.listTopicSnapshots = stubSimpleCallWithCallback(expectedResponse); @@ -1735,7 +1737,7 @@ describe('v1.PublisherClient', () => { } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1755,20 +1757,20 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listTopicSnapshots = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.listTopicSnapshots(request), expectedError); const actualRequest = ( @@ -1786,16 +1788,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.descriptors.page.listTopicSnapshots.createStream = stubPageStreamingCall(expectedResponse); @@ -1817,14 +1819,14 @@ describe('v1.PublisherClient', () => { assert( (client.descriptors.page.listTopicSnapshots.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listTopicSnapshots, request) + .calledWith(client.innerApiCalls.listTopicSnapshots, request), ); assert( (client.descriptors.page.listTopicSnapshots.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1833,16 +1835,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listTopicSnapshots.createStream = stubPageStreamingCall(undefined, expectedError); @@ -1863,14 +1865,14 @@ describe('v1.PublisherClient', () => { assert( (client.descriptors.page.listTopicSnapshots.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listTopicSnapshots, request) + .calledWith(client.innerApiCalls.listTopicSnapshots, request), ); assert( (client.descriptors.page.listTopicSnapshots.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1879,16 +1881,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.descriptors.page.listTopicSnapshots.asyncIterate = stubAsyncIterationCall(expectedResponse); @@ -1902,14 +1904,14 @@ describe('v1.PublisherClient', () => { ( client.descriptors.page.listTopicSnapshots.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listTopicSnapshots.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1918,16 +1920,16 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListTopicSnapshotsRequest() + new protos.google.pubsub.v1.ListTopicSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListTopicSnapshotsRequest', - ['topic'] + ['topic'], ); request.topic = defaultValue1; - const expectedHeaderRequestParams = `topic=${defaultValue1}`; + const expectedHeaderRequestParams = `topic=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listTopicSnapshots.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -1942,14 +1944,14 @@ describe('v1.PublisherClient', () => { ( client.descriptors.page.listTopicSnapshots.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listTopicSnapshots.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); }); @@ -1959,9 +1961,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -1973,7 +1975,7 @@ describe('v1.PublisherClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); const response = await client.getIamPolicy(request, expectedOptions); @@ -1981,7 +1983,7 @@ describe('v1.PublisherClient', () => { assert( (client.iamClient.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes getIamPolicy without error using callback', async () => { @@ -1989,9 +1991,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2003,25 +2005,25 @@ describe('v1.PublisherClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.getIamPolicy = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.getIamPolicy( + void client.getIamPolicy( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.Policy | null + result?: IamProtos.google.iam.v1.Policy | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2033,9 +2035,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2050,12 +2052,12 @@ describe('v1.PublisherClient', () => { client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); await assert.rejects( client.getIamPolicy(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -2065,9 +2067,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2079,7 +2081,7 @@ describe('v1.PublisherClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); const response = await client.setIamPolicy(request, expectedOptions); @@ -2087,7 +2089,7 @@ describe('v1.PublisherClient', () => { assert( (client.iamClient.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes setIamPolicy without error using callback', async () => { @@ -2095,9 +2097,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2109,25 +2111,25 @@ describe('v1.PublisherClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.setIamPolicy = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.setIamPolicy( + void client.setIamPolicy( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.Policy | null + result?: IamProtos.google.iam.v1.Policy | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2139,9 +2141,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2156,12 +2158,12 @@ describe('v1.PublisherClient', () => { client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); await assert.rejects( client.setIamPolicy(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -2171,9 +2173,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2185,18 +2187,18 @@ describe('v1.PublisherClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), ); client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); const response = await client.testIamPermissions( request, - expectedOptions + expectedOptions, ); assert.deepStrictEqual(response, [expectedResponse]); assert( (client.iamClient.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes testIamPermissions without error using callback', async () => { @@ -2204,9 +2206,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2218,25 +2220,25 @@ describe('v1.PublisherClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), ); client.iamClient.testIamPermissions = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.testIamPermissions( + void client.testIamPermissions( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2248,9 +2250,9 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2264,22 +2266,22 @@ describe('v1.PublisherClient', () => { const expectedError = new Error('expected'); client.iamClient.testIamPermissions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.testIamPermissions(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); describe('Path templates', () => { - describe('project', () => { + describe('project', async () => { const fakePath = '/rendered/path/project'; const expectedParameters = { project: 'projectValue', @@ -2288,7 +2290,7 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2302,7 +2304,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.projectPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2312,12 +2314,12 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.projectPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('projectTopic', () => { + describe('projectTopic', async () => { const fakePath = '/rendered/path/projectTopic'; const expectedParameters = { project: 'projectValue', @@ -2327,7 +2329,7 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectTopicPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2341,7 +2343,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2351,7 +2353,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2361,12 +2363,12 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('schema', () => { + describe('schema', async () => { const fakePath = '/rendered/path/schema'; const expectedParameters = { project: 'projectValue', @@ -2376,7 +2378,7 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.schemaPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2390,7 +2392,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.schemaPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2400,7 +2402,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.schemaPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2410,12 +2412,12 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.schemaPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('snapshot', () => { + describe('snapshot', async () => { const fakePath = '/rendered/path/snapshot'; const expectedParameters = { project: 'projectValue', @@ -2425,7 +2427,7 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.snapshotPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2439,7 +2441,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2449,7 +2451,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2459,12 +2461,12 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('subscription', () => { + describe('subscription', async () => { const fakePath = '/rendered/path/subscription'; const expectedParameters = { project: 'projectValue', @@ -2474,7 +2476,7 @@ describe('v1.PublisherClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.subscriptionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2485,13 +2487,13 @@ describe('v1.PublisherClient', () => { it('subscriptionPath', () => { const result = client.subscriptionPath( 'projectValue', - 'subscriptionValue' + 'subscriptionValue', ); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.subscriptionPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2501,7 +2503,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.subscriptionPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2511,7 +2513,7 @@ describe('v1.PublisherClient', () => { assert( (client.pathTemplates.subscriptionPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); diff --git a/test/gapic_schema_service_v1.ts b/test/gapic_schema_service_v1.ts index a01b05f34..46c951ae3 100644 --- a/test/gapic_schema_service_v1.ts +++ b/test/gapic_schema_service_v1.ts @@ -30,7 +30,7 @@ import {protobuf, IamProtos} from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects const root = protobuf.Root.fromJSON( - require('../protos/protos.json') + require('../protos/protos.json'), ).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -47,7 +47,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -59,7 +59,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -68,7 +68,7 @@ function stubSimpleCallWithCallback( function stubPageStreamingCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { const pagingStub = sinon.stub(); if (responses) { @@ -106,7 +106,7 @@ function stubPageStreamingCall( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -252,9 +252,11 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(err => { + throw err; + }); assert(client.schemaServiceStub); - client.close().then(() => { + void client.close().then(() => { done(); }); }); @@ -265,7 +267,7 @@ describe('v1.SchemaServiceClient', () => { projectId: 'bogus', }); assert.strictEqual(client.schemaServiceStub, undefined); - client.close().then(() => { + void client.close().then(() => { done(); }); }); @@ -311,18 +313,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSchemaRequest() + new protos.google.pubsub.v1.CreateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.createSchema = stubSimpleCall(expectedResponse); const [response] = await client.createSchema(request); @@ -342,18 +344,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSchemaRequest() + new protos.google.pubsub.v1.CreateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.createSchema = stubSimpleCallWithCallback(expectedResponse); @@ -362,14 +364,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema | null + result?: protos.google.pubsub.v1.ISchema | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -389,20 +391,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSchemaRequest() + new protos.google.pubsub.v1.CreateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createSchema = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.createSchema(request), expectedError); const actualRequest = ( @@ -420,17 +422,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSchemaRequest() + new protos.google.pubsub.v1.CreateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.createSchema(request), expectedError); }); }); @@ -441,18 +443,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSchemaRequest() + new protos.google.pubsub.v1.GetSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.getSchema = stubSimpleCall(expectedResponse); const [response] = await client.getSchema(request); @@ -472,18 +474,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSchemaRequest() + new protos.google.pubsub.v1.GetSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.getSchema = stubSimpleCallWithCallback(expectedResponse); @@ -492,14 +494,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema | null + result?: protos.google.pubsub.v1.ISchema | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -519,16 +521,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSchemaRequest() + new protos.google.pubsub.v1.GetSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getSchema = stubSimpleCall(undefined, expectedError); await assert.rejects(client.getSchema(request), expectedError); @@ -547,17 +549,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSchemaRequest() + new protos.google.pubsub.v1.GetSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.getSchema(request), expectedError); }); }); @@ -568,18 +570,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CommitSchemaRequest() + new protos.google.pubsub.v1.CommitSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CommitSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.commitSchema = stubSimpleCall(expectedResponse); const [response] = await client.commitSchema(request); @@ -599,18 +601,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CommitSchemaRequest() + new protos.google.pubsub.v1.CommitSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CommitSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.commitSchema = stubSimpleCallWithCallback(expectedResponse); @@ -619,14 +621,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema | null + result?: protos.google.pubsub.v1.ISchema | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -646,20 +648,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CommitSchemaRequest() + new protos.google.pubsub.v1.CommitSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CommitSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.commitSchema = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.commitSchema(request), expectedError); const actualRequest = ( @@ -677,17 +679,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CommitSchemaRequest() + new protos.google.pubsub.v1.CommitSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CommitSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.commitSchema(request), expectedError); }); }); @@ -698,18 +700,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.RollbackSchemaRequest() + new protos.google.pubsub.v1.RollbackSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.RollbackSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.rollbackSchema = stubSimpleCall(expectedResponse); const [response] = await client.rollbackSchema(request); @@ -729,18 +731,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.RollbackSchemaRequest() + new protos.google.pubsub.v1.RollbackSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.RollbackSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.rollbackSchema = stubSimpleCallWithCallback(expectedResponse); @@ -749,14 +751,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema | null + result?: protos.google.pubsub.v1.ISchema | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -776,20 +778,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.RollbackSchemaRequest() + new protos.google.pubsub.v1.RollbackSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.RollbackSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.rollbackSchema = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.rollbackSchema(request), expectedError); const actualRequest = ( @@ -807,17 +809,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.RollbackSchemaRequest() + new protos.google.pubsub.v1.RollbackSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.RollbackSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.rollbackSchema(request), expectedError); }); }); @@ -828,18 +830,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRevisionRequest() + new protos.google.pubsub.v1.DeleteSchemaRevisionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRevisionRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.deleteSchemaRevision = stubSimpleCall(expectedResponse); @@ -860,18 +862,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRevisionRequest() + new protos.google.pubsub.v1.DeleteSchemaRevisionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRevisionRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Schema() + new protos.google.pubsub.v1.Schema(), ); client.innerApiCalls.deleteSchemaRevision = stubSimpleCallWithCallback(expectedResponse); @@ -880,14 +882,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema | null + result?: protos.google.pubsub.v1.ISchema | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -907,20 +909,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRevisionRequest() + new protos.google.pubsub.v1.DeleteSchemaRevisionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRevisionRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteSchemaRevision = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.deleteSchemaRevision(request), expectedError); const actualRequest = ( @@ -938,17 +940,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRevisionRequest() + new protos.google.pubsub.v1.DeleteSchemaRevisionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRevisionRequest', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.deleteSchemaRevision(request), expectedError); }); }); @@ -959,18 +961,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRequest() + new protos.google.pubsub.v1.DeleteSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteSchema = stubSimpleCall(expectedResponse); const [response] = await client.deleteSchema(request); @@ -990,18 +992,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRequest() + new protos.google.pubsub.v1.DeleteSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteSchema = stubSimpleCallWithCallback(expectedResponse); @@ -1010,14 +1012,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1037,20 +1039,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRequest() + new protos.google.pubsub.v1.DeleteSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteSchema = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.deleteSchema(request), expectedError); const actualRequest = ( @@ -1068,17 +1070,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSchemaRequest() + new protos.google.pubsub.v1.DeleteSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSchemaRequest', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.deleteSchema(request), expectedError); }); }); @@ -1089,18 +1091,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateSchemaRequest() + new protos.google.pubsub.v1.ValidateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.ValidateSchemaResponse() + new protos.google.pubsub.v1.ValidateSchemaResponse(), ); client.innerApiCalls.validateSchema = stubSimpleCall(expectedResponse); const [response] = await client.validateSchema(request); @@ -1120,18 +1122,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateSchemaRequest() + new protos.google.pubsub.v1.ValidateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.ValidateSchemaResponse() + new protos.google.pubsub.v1.ValidateSchemaResponse(), ); client.innerApiCalls.validateSchema = stubSimpleCallWithCallback(expectedResponse); @@ -1140,14 +1142,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.IValidateSchemaResponse | null + result?: protos.google.pubsub.v1.IValidateSchemaResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1167,20 +1169,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateSchemaRequest() + new protos.google.pubsub.v1.ValidateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.validateSchema = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.validateSchema(request), expectedError); const actualRequest = ( @@ -1198,17 +1200,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateSchemaRequest() + new protos.google.pubsub.v1.ValidateSchemaRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateSchemaRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.validateSchema(request), expectedError); }); }); @@ -1219,18 +1221,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateMessageRequest() + new protos.google.pubsub.v1.ValidateMessageRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateMessageRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.ValidateMessageResponse() + new protos.google.pubsub.v1.ValidateMessageResponse(), ); client.innerApiCalls.validateMessage = stubSimpleCall(expectedResponse); const [response] = await client.validateMessage(request); @@ -1250,18 +1252,18 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateMessageRequest() + new protos.google.pubsub.v1.ValidateMessageRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateMessageRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.ValidateMessageResponse() + new protos.google.pubsub.v1.ValidateMessageResponse(), ); client.innerApiCalls.validateMessage = stubSimpleCallWithCallback(expectedResponse); @@ -1270,14 +1272,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.IValidateMessageResponse | null + result?: protos.google.pubsub.v1.IValidateMessageResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1297,20 +1299,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateMessageRequest() + new protos.google.pubsub.v1.ValidateMessageRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateMessageRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.validateMessage = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.validateMessage(request), expectedError); const actualRequest = ( @@ -1328,17 +1330,17 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ValidateMessageRequest() + new protos.google.pubsub.v1.ValidateMessageRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ValidateMessageRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.validateMessage(request), expectedError); }); }); @@ -1349,16 +1351,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1382,16 +1384,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1404,14 +1406,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema[] | null + result?: protos.google.pubsub.v1.ISchema[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1431,20 +1433,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listSchemas = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.listSchemas(request), expectedError); const actualRequest = ( @@ -1462,16 +1464,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1497,14 +1499,14 @@ describe('v1.SchemaServiceClient', () => { assert( (client.descriptors.page.listSchemas.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSchemas, request) + .calledWith(client.innerApiCalls.listSchemas, request), ); assert( (client.descriptors.page.listSchemas.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1513,20 +1515,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSchemas.createStream = stubPageStreamingCall( undefined, - expectedError + expectedError, ); const stream = client.listSchemasStream(request); const promise = new Promise((resolve, reject) => { @@ -1545,14 +1547,14 @@ describe('v1.SchemaServiceClient', () => { assert( (client.descriptors.page.listSchemas.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSchemas, request) + .calledWith(client.innerApiCalls.listSchemas, request), ); assert( (client.descriptors.page.listSchemas.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1561,16 +1563,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1586,16 +1588,16 @@ describe('v1.SchemaServiceClient', () => { assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( (client.descriptors.page.listSchemas.asyncIterate as SinonStub).getCall( - 0 + 0, ).args[1], - request + request, ); assert( (client.descriptors.page.listSchemas.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1604,20 +1606,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemasRequest() + new protos.google.pubsub.v1.ListSchemasRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemasRequest', - ['parent'] + ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSchemas.asyncIterate = stubAsyncIterationCall( undefined, - expectedError + expectedError, ); const iterable = client.listSchemasAsync(request); await assert.rejects(async () => { @@ -1628,16 +1630,16 @@ describe('v1.SchemaServiceClient', () => { }); assert.deepStrictEqual( (client.descriptors.page.listSchemas.asyncIterate as SinonStub).getCall( - 0 + 0, ).args[1], - request + request, ); assert( (client.descriptors.page.listSchemas.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); }); @@ -1648,16 +1650,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1682,16 +1684,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1704,14 +1706,14 @@ describe('v1.SchemaServiceClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISchema[] | null + result?: protos.google.pubsub.v1.ISchema[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1731,20 +1733,20 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listSchemaRevisions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.listSchemaRevisions(request), expectedError); const actualRequest = ( @@ -1762,16 +1764,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1797,14 +1799,14 @@ describe('v1.SchemaServiceClient', () => { assert( (client.descriptors.page.listSchemaRevisions.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSchemaRevisions, request) + .calledWith(client.innerApiCalls.listSchemaRevisions, request), ); assert( (client.descriptors.page.listSchemaRevisions.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1813,16 +1815,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSchemaRevisions.createStream = stubPageStreamingCall(undefined, expectedError); @@ -1843,14 +1845,14 @@ describe('v1.SchemaServiceClient', () => { assert( (client.descriptors.page.listSchemaRevisions.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSchemaRevisions, request) + .calledWith(client.innerApiCalls.listSchemaRevisions, request), ); assert( (client.descriptors.page.listSchemaRevisions.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1859,16 +1861,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Schema()), generateSampleMessage(new protos.google.pubsub.v1.Schema()), @@ -1886,14 +1888,14 @@ describe('v1.SchemaServiceClient', () => { ( client.descriptors.page.listSchemaRevisions.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listSchemaRevisions.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -1902,16 +1904,16 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSchemaRevisionsRequest() + new protos.google.pubsub.v1.ListSchemaRevisionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSchemaRevisionsRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSchemaRevisions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -1926,14 +1928,14 @@ describe('v1.SchemaServiceClient', () => { ( client.descriptors.page.listSchemaRevisions.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listSchemaRevisions.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); }); @@ -1943,9 +1945,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -1957,7 +1959,7 @@ describe('v1.SchemaServiceClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); const response = await client.getIamPolicy(request, expectedOptions); @@ -1965,7 +1967,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.iamClient.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes getIamPolicy without error using callback', async () => { @@ -1973,9 +1975,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -1987,25 +1989,25 @@ describe('v1.SchemaServiceClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.getIamPolicy = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.getIamPolicy( + void client.getIamPolicy( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.Policy | null + result?: IamProtos.google.iam.v1.Policy | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2017,9 +2019,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2034,12 +2036,12 @@ describe('v1.SchemaServiceClient', () => { client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); await assert.rejects( client.getIamPolicy(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -2049,9 +2051,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2063,7 +2065,7 @@ describe('v1.SchemaServiceClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); const response = await client.setIamPolicy(request, expectedOptions); @@ -2071,7 +2073,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.iamClient.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes setIamPolicy without error using callback', async () => { @@ -2079,9 +2081,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2093,25 +2095,25 @@ describe('v1.SchemaServiceClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.setIamPolicy = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.setIamPolicy( + void client.setIamPolicy( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.Policy | null + result?: IamProtos.google.iam.v1.Policy | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2123,9 +2125,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2140,12 +2142,12 @@ describe('v1.SchemaServiceClient', () => { client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); await assert.rejects( client.setIamPolicy(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -2155,9 +2157,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2169,18 +2171,18 @@ describe('v1.SchemaServiceClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), ); client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); const response = await client.testIamPermissions( request, - expectedOptions + expectedOptions, ); assert.deepStrictEqual(response, [expectedResponse]); assert( (client.iamClient.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes testIamPermissions without error using callback', async () => { @@ -2188,9 +2190,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2202,25 +2204,25 @@ describe('v1.SchemaServiceClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), ); client.iamClient.testIamPermissions = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.testIamPermissions( + void client.testIamPermissions( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2232,9 +2234,9 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2248,22 +2250,22 @@ describe('v1.SchemaServiceClient', () => { const expectedError = new Error('expected'); client.iamClient.testIamPermissions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.testIamPermissions(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); describe('Path templates', () => { - describe('project', () => { + describe('project', async () => { const fakePath = '/rendered/path/project'; const expectedParameters = { project: 'projectValue', @@ -2272,7 +2274,7 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2286,7 +2288,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.projectPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2296,12 +2298,12 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.projectPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('projectTopic', () => { + describe('projectTopic', async () => { const fakePath = '/rendered/path/projectTopic'; const expectedParameters = { project: 'projectValue', @@ -2311,7 +2313,7 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectTopicPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2325,7 +2327,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2335,7 +2337,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2345,12 +2347,12 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('schema', () => { + describe('schema', async () => { const fakePath = '/rendered/path/schema'; const expectedParameters = { project: 'projectValue', @@ -2360,7 +2362,7 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.schemaPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2374,7 +2376,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.schemaPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2384,7 +2386,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.schemaPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2394,12 +2396,12 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.schemaPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('snapshot', () => { + describe('snapshot', async () => { const fakePath = '/rendered/path/snapshot'; const expectedParameters = { project: 'projectValue', @@ -2409,7 +2411,7 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.snapshotPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2423,7 +2425,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2433,7 +2435,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2443,12 +2445,12 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('subscription', () => { + describe('subscription', async () => { const fakePath = '/rendered/path/subscription'; const expectedParameters = { project: 'projectValue', @@ -2458,7 +2460,7 @@ describe('v1.SchemaServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.subscriptionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2469,13 +2471,13 @@ describe('v1.SchemaServiceClient', () => { it('subscriptionPath', () => { const result = client.subscriptionPath( 'projectValue', - 'subscriptionValue' + 'subscriptionValue', ); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.subscriptionPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -2485,7 +2487,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.subscriptionPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -2495,7 +2497,7 @@ describe('v1.SchemaServiceClient', () => { assert( (client.pathTemplates.subscriptionPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); diff --git a/test/gapic_subscriber_v1.ts b/test/gapic_subscriber_v1.ts index 92c5fc49a..55667c97c 100644 --- a/test/gapic_subscriber_v1.ts +++ b/test/gapic_subscriber_v1.ts @@ -30,7 +30,7 @@ import {protobuf, IamProtos} from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects const root = protobuf.Root.fromJSON( - require('../protos/protos.json') + require('../protos/protos.json'), ).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -47,7 +47,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -59,7 +59,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -68,7 +68,7 @@ function stubSimpleCallWithCallback( function stubBidiStreamingCall( response?: ResponseType, - error?: Error + error?: Error, ) { const transformStub = error ? sinon.stub().callsArgWith(2, error) @@ -82,7 +82,7 @@ function stubBidiStreamingCall( function stubPageStreamingCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { const pagingStub = sinon.stub(); if (responses) { @@ -120,7 +120,7 @@ function stubPageStreamingCall( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -264,9 +264,11 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(err => { + throw err; + }); assert(client.subscriberStub); - client.close().then(() => { + void client.close().then(() => { done(); }); }); @@ -277,7 +279,7 @@ describe('v1.SubscriberClient', () => { projectId: 'bogus', }); assert.strictEqual(client.subscriberStub, undefined); - client.close().then(() => { + void client.close().then(() => { done(); }); }); @@ -323,18 +325,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.Subscription', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); client.innerApiCalls.createSubscription = stubSimpleCall(expectedResponse); @@ -355,18 +357,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.Subscription', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); client.innerApiCalls.createSubscription = stubSimpleCallWithCallback(expectedResponse); @@ -375,14 +377,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISubscription | null + result?: protos.google.pubsub.v1.ISubscription | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -402,20 +404,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.Subscription', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createSubscription = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.createSubscription(request), expectedError); const actualRequest = ( @@ -433,17 +435,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.Subscription', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.createSubscription(request), expectedError); }); }); @@ -454,18 +456,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSubscriptionRequest() + new protos.google.pubsub.v1.GetSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); client.innerApiCalls.getSubscription = stubSimpleCall(expectedResponse); const [response] = await client.getSubscription(request); @@ -485,18 +487,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSubscriptionRequest() + new protos.google.pubsub.v1.GetSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); client.innerApiCalls.getSubscription = stubSimpleCallWithCallback(expectedResponse); @@ -505,14 +507,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISubscription | null + result?: protos.google.pubsub.v1.ISubscription | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -532,20 +534,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSubscriptionRequest() + new protos.google.pubsub.v1.GetSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getSubscription = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.getSubscription(request), expectedError); const actualRequest = ( @@ -563,17 +565,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSubscriptionRequest() + new protos.google.pubsub.v1.GetSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.getSubscription(request), expectedError); }); }); @@ -584,19 +586,19 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSubscriptionRequest() + new protos.google.pubsub.v1.UpdateSubscriptionRequest(), ); request.subscription ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSubscriptionRequest', - ['subscription', 'name'] + ['subscription', 'name'], ); request.subscription.name = defaultValue1; - const expectedHeaderRequestParams = `subscription.name=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription.name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); client.innerApiCalls.updateSubscription = stubSimpleCall(expectedResponse); @@ -617,19 +619,19 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSubscriptionRequest() + new protos.google.pubsub.v1.UpdateSubscriptionRequest(), ); request.subscription ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSubscriptionRequest', - ['subscription', 'name'] + ['subscription', 'name'], ); request.subscription.name = defaultValue1; - const expectedHeaderRequestParams = `subscription.name=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription.name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Subscription() + new protos.google.pubsub.v1.Subscription(), ); client.innerApiCalls.updateSubscription = stubSimpleCallWithCallback(expectedResponse); @@ -638,14 +640,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISubscription | null + result?: protos.google.pubsub.v1.ISubscription | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -665,21 +667,21 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSubscriptionRequest() + new protos.google.pubsub.v1.UpdateSubscriptionRequest(), ); request.subscription ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSubscriptionRequest', - ['subscription', 'name'] + ['subscription', 'name'], ); request.subscription.name = defaultValue1; - const expectedHeaderRequestParams = `subscription.name=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription.name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateSubscription = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.updateSubscription(request), expectedError); const actualRequest = ( @@ -697,18 +699,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSubscriptionRequest() + new protos.google.pubsub.v1.UpdateSubscriptionRequest(), ); request.subscription ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSubscriptionRequest', - ['subscription', 'name'] + ['subscription', 'name'], ); request.subscription.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.updateSubscription(request), expectedError); }); }); @@ -719,18 +721,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSubscriptionRequest() + new protos.google.pubsub.v1.DeleteSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteSubscription = stubSimpleCall(expectedResponse); @@ -751,18 +753,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSubscriptionRequest() + new protos.google.pubsub.v1.DeleteSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteSubscription = stubSimpleCallWithCallback(expectedResponse); @@ -771,14 +773,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -798,20 +800,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSubscriptionRequest() + new protos.google.pubsub.v1.DeleteSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteSubscription = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.deleteSubscription(request), expectedError); const actualRequest = ( @@ -829,17 +831,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSubscriptionRequest() + new protos.google.pubsub.v1.DeleteSubscriptionRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSubscriptionRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.deleteSubscription(request), expectedError); }); }); @@ -850,18 +852,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyAckDeadlineRequest() + new protos.google.pubsub.v1.ModifyAckDeadlineRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyAckDeadlineRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.modifyAckDeadline = stubSimpleCall(expectedResponse); const [response] = await client.modifyAckDeadline(request); @@ -881,18 +883,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyAckDeadlineRequest() + new protos.google.pubsub.v1.ModifyAckDeadlineRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyAckDeadlineRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.modifyAckDeadline = stubSimpleCallWithCallback(expectedResponse); @@ -901,14 +903,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -928,20 +930,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyAckDeadlineRequest() + new protos.google.pubsub.v1.ModifyAckDeadlineRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyAckDeadlineRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.modifyAckDeadline = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.modifyAckDeadline(request), expectedError); const actualRequest = ( @@ -959,17 +961,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyAckDeadlineRequest() + new protos.google.pubsub.v1.ModifyAckDeadlineRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyAckDeadlineRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.modifyAckDeadline(request), expectedError); }); }); @@ -980,18 +982,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.AcknowledgeRequest() + new protos.google.pubsub.v1.AcknowledgeRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.AcknowledgeRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.acknowledge = stubSimpleCall(expectedResponse); const [response] = await client.acknowledge(request); @@ -1011,18 +1013,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.AcknowledgeRequest() + new protos.google.pubsub.v1.AcknowledgeRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.AcknowledgeRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.acknowledge = stubSimpleCallWithCallback(expectedResponse); @@ -1031,14 +1033,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1058,20 +1060,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.AcknowledgeRequest() + new protos.google.pubsub.v1.AcknowledgeRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.AcknowledgeRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.acknowledge = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.acknowledge(request), expectedError); const actualRequest = ( @@ -1089,17 +1091,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.AcknowledgeRequest() + new protos.google.pubsub.v1.AcknowledgeRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.AcknowledgeRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.acknowledge(request), expectedError); }); }); @@ -1110,18 +1112,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PullRequest() + new protos.google.pubsub.v1.PullRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PullRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.PullResponse() + new protos.google.pubsub.v1.PullResponse(), ); client.innerApiCalls.pull = stubSimpleCall(expectedResponse); const [response] = await client.pull(request); @@ -1140,18 +1142,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PullRequest() + new protos.google.pubsub.v1.PullRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PullRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.PullResponse() + new protos.google.pubsub.v1.PullResponse(), ); client.innerApiCalls.pull = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { @@ -1159,14 +1161,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.IPullResponse | null + result?: protos.google.pubsub.v1.IPullResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1185,16 +1187,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PullRequest() + new protos.google.pubsub.v1.PullRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PullRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.pull = stubSimpleCall(undefined, expectedError); await assert.rejects(client.pull(request), expectedError); @@ -1212,17 +1214,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.PullRequest() + new protos.google.pubsub.v1.PullRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.PullRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.pull(request), expectedError); }); }); @@ -1233,18 +1235,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyPushConfigRequest() + new protos.google.pubsub.v1.ModifyPushConfigRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyPushConfigRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.modifyPushConfig = stubSimpleCall(expectedResponse); const [response] = await client.modifyPushConfig(request); @@ -1264,18 +1266,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyPushConfigRequest() + new protos.google.pubsub.v1.ModifyPushConfigRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyPushConfigRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.modifyPushConfig = stubSimpleCallWithCallback(expectedResponse); @@ -1284,14 +1286,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1311,20 +1313,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyPushConfigRequest() + new protos.google.pubsub.v1.ModifyPushConfigRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyPushConfigRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.modifyPushConfig = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.modifyPushConfig(request), expectedError); const actualRequest = ( @@ -1342,17 +1344,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ModifyPushConfigRequest() + new protos.google.pubsub.v1.ModifyPushConfigRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ModifyPushConfigRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.modifyPushConfig(request), expectedError); }); }); @@ -1363,18 +1365,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSnapshotRequest() + new protos.google.pubsub.v1.GetSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; - const expectedHeaderRequestParams = `snapshot=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Snapshot() + new protos.google.pubsub.v1.Snapshot(), ); client.innerApiCalls.getSnapshot = stubSimpleCall(expectedResponse); const [response] = await client.getSnapshot(request); @@ -1394,18 +1396,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSnapshotRequest() + new protos.google.pubsub.v1.GetSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; - const expectedHeaderRequestParams = `snapshot=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Snapshot() + new protos.google.pubsub.v1.Snapshot(), ); client.innerApiCalls.getSnapshot = stubSimpleCallWithCallback(expectedResponse); @@ -1414,14 +1416,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISnapshot | null + result?: protos.google.pubsub.v1.ISnapshot | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1441,20 +1443,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSnapshotRequest() + new protos.google.pubsub.v1.GetSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; - const expectedHeaderRequestParams = `snapshot=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getSnapshot = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.getSnapshot(request), expectedError); const actualRequest = ( @@ -1472,17 +1474,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.GetSnapshotRequest() + new protos.google.pubsub.v1.GetSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.GetSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.getSnapshot(request), expectedError); }); }); @@ -1493,18 +1495,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSnapshotRequest() + new protos.google.pubsub.v1.CreateSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSnapshotRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Snapshot() + new protos.google.pubsub.v1.Snapshot(), ); client.innerApiCalls.createSnapshot = stubSimpleCall(expectedResponse); const [response] = await client.createSnapshot(request); @@ -1524,18 +1526,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSnapshotRequest() + new protos.google.pubsub.v1.CreateSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSnapshotRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Snapshot() + new protos.google.pubsub.v1.Snapshot(), ); client.innerApiCalls.createSnapshot = stubSimpleCallWithCallback(expectedResponse); @@ -1544,14 +1546,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISnapshot | null + result?: protos.google.pubsub.v1.ISnapshot | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1571,20 +1573,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSnapshotRequest() + new protos.google.pubsub.v1.CreateSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSnapshotRequest', - ['name'] + ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createSnapshot = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.createSnapshot(request), expectedError); const actualRequest = ( @@ -1602,17 +1604,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.CreateSnapshotRequest() + new protos.google.pubsub.v1.CreateSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.CreateSnapshotRequest', - ['name'] + ['name'], ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.createSnapshot(request), expectedError); }); }); @@ -1623,19 +1625,19 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSnapshotRequest() + new protos.google.pubsub.v1.UpdateSnapshotRequest(), ); request.snapshot ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSnapshotRequest', - ['snapshot', 'name'] + ['snapshot', 'name'], ); request.snapshot.name = defaultValue1; - const expectedHeaderRequestParams = `snapshot.name=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot.name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Snapshot() + new protos.google.pubsub.v1.Snapshot(), ); client.innerApiCalls.updateSnapshot = stubSimpleCall(expectedResponse); const [response] = await client.updateSnapshot(request); @@ -1655,19 +1657,19 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSnapshotRequest() + new protos.google.pubsub.v1.UpdateSnapshotRequest(), ); request.snapshot ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSnapshotRequest', - ['snapshot', 'name'] + ['snapshot', 'name'], ); request.snapshot.name = defaultValue1; - const expectedHeaderRequestParams = `snapshot.name=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot.name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.Snapshot() + new protos.google.pubsub.v1.Snapshot(), ); client.innerApiCalls.updateSnapshot = stubSimpleCallWithCallback(expectedResponse); @@ -1676,14 +1678,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISnapshot | null + result?: protos.google.pubsub.v1.ISnapshot | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1703,21 +1705,21 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSnapshotRequest() + new protos.google.pubsub.v1.UpdateSnapshotRequest(), ); request.snapshot ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSnapshotRequest', - ['snapshot', 'name'] + ['snapshot', 'name'], ); request.snapshot.name = defaultValue1; - const expectedHeaderRequestParams = `snapshot.name=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot.name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateSnapshot = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.updateSnapshot(request), expectedError); const actualRequest = ( @@ -1735,18 +1737,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.UpdateSnapshotRequest() + new protos.google.pubsub.v1.UpdateSnapshotRequest(), ); request.snapshot ??= {}; const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.UpdateSnapshotRequest', - ['snapshot', 'name'] + ['snapshot', 'name'], ); request.snapshot.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.updateSnapshot(request), expectedError); }); }); @@ -1757,18 +1759,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSnapshotRequest() + new protos.google.pubsub.v1.DeleteSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; - const expectedHeaderRequestParams = `snapshot=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteSnapshot = stubSimpleCall(expectedResponse); const [response] = await client.deleteSnapshot(request); @@ -1788,18 +1790,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSnapshotRequest() + new protos.google.pubsub.v1.DeleteSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; - const expectedHeaderRequestParams = `snapshot=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteSnapshot = stubSimpleCallWithCallback(expectedResponse); @@ -1808,14 +1810,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.protobuf.IEmpty | null + result?: protos.google.protobuf.IEmpty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1835,20 +1837,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSnapshotRequest() + new protos.google.pubsub.v1.DeleteSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; - const expectedHeaderRequestParams = `snapshot=${defaultValue1}`; + const expectedHeaderRequestParams = `snapshot=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteSnapshot = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.deleteSnapshot(request), expectedError); const actualRequest = ( @@ -1866,17 +1868,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.DeleteSnapshotRequest() + new protos.google.pubsub.v1.DeleteSnapshotRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.DeleteSnapshotRequest', - ['snapshot'] + ['snapshot'], ); request.snapshot = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.deleteSnapshot(request), expectedError); }); }); @@ -1887,18 +1889,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.SeekRequest() + new protos.google.pubsub.v1.SeekRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.SeekRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.SeekResponse() + new protos.google.pubsub.v1.SeekResponse(), ); client.innerApiCalls.seek = stubSimpleCall(expectedResponse); const [response] = await client.seek(request); @@ -1917,18 +1919,18 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.SeekRequest() + new protos.google.pubsub.v1.SeekRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.SeekRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.SeekResponse() + new protos.google.pubsub.v1.SeekResponse(), ); client.innerApiCalls.seek = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { @@ -1936,14 +1938,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISeekResponse | null + result?: protos.google.pubsub.v1.ISeekResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -1962,16 +1964,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.SeekRequest() + new protos.google.pubsub.v1.SeekRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.SeekRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; - const expectedHeaderRequestParams = `subscription=${defaultValue1}`; + const expectedHeaderRequestParams = `subscription=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.seek = stubSimpleCall(undefined, expectedError); await assert.rejects(client.seek(request), expectedError); @@ -1989,17 +1991,17 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.SeekRequest() + new protos.google.pubsub.v1.SeekRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.SeekRequest', - ['subscription'] + ['subscription'], ); request.subscription = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + void client.close(); await assert.rejects(client.seek(request), expectedError); }); }); @@ -2010,13 +2012,13 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.StreamingPullRequest() + new protos.google.pubsub.v1.StreamingPullRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.pubsub.v1.StreamingPullResponse() + new protos.google.pubsub.v1.StreamingPullResponse(), ); client.innerApiCalls.streamingPull = stubBidiStreamingCall(expectedResponse); @@ -2026,7 +2028,7 @@ describe('v1.SubscriberClient', () => { 'data', (response: protos.google.pubsub.v1.StreamingPullResponse) => { resolve(response); - } + }, ); stream.on('error', (err: Error) => { reject(err); @@ -2039,12 +2041,12 @@ describe('v1.SubscriberClient', () => { assert( (client.innerApiCalls.streamingPull as SinonStub) .getCall(0) - .calledWith(null) + .calledWith(null), ); assert.deepStrictEqual( ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) .args[0], - request + request, ); }); @@ -2053,14 +2055,14 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.StreamingPullRequest() + new protos.google.pubsub.v1.StreamingPullRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.streamingPull = stubBidiStreamingCall( undefined, - expectedError + expectedError, ); const stream = client.streamingPull(); const promise = new Promise((resolve, reject) => { @@ -2068,7 +2070,7 @@ describe('v1.SubscriberClient', () => { 'data', (response: protos.google.pubsub.v1.StreamingPullResponse) => { resolve(response); - } + }, ); stream.on('error', (err: Error) => { reject(err); @@ -2080,12 +2082,12 @@ describe('v1.SubscriberClient', () => { assert( (client.innerApiCalls.streamingPull as SinonStub) .getCall(0) - .calledWith(null) + .calledWith(null), ); assert.deepStrictEqual( ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) .args[0], - request + request, ); }); }); @@ -2096,16 +2098,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Subscription()), generateSampleMessage(new protos.google.pubsub.v1.Subscription()), @@ -2129,16 +2131,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Subscription()), generateSampleMessage(new protos.google.pubsub.v1.Subscription()), @@ -2151,14 +2153,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISubscription[] | null + result?: protos.google.pubsub.v1.ISubscription[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2178,20 +2180,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listSubscriptions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.listSubscriptions(request), expectedError); const actualRequest = ( @@ -2209,16 +2211,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Subscription()), generateSampleMessage(new protos.google.pubsub.v1.Subscription()), @@ -2244,14 +2246,14 @@ describe('v1.SubscriberClient', () => { assert( (client.descriptors.page.listSubscriptions.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSubscriptions, request) + .calledWith(client.innerApiCalls.listSubscriptions, request), ); assert( (client.descriptors.page.listSubscriptions.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -2260,16 +2262,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSubscriptions.createStream = stubPageStreamingCall(undefined, expectedError); @@ -2290,14 +2292,14 @@ describe('v1.SubscriberClient', () => { assert( (client.descriptors.page.listSubscriptions.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSubscriptions, request) + .calledWith(client.innerApiCalls.listSubscriptions, request), ); assert( (client.descriptors.page.listSubscriptions.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -2306,16 +2308,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Subscription()), generateSampleMessage(new protos.google.pubsub.v1.Subscription()), @@ -2333,14 +2335,14 @@ describe('v1.SubscriberClient', () => { ( client.descriptors.page.listSubscriptions.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listSubscriptions.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -2349,16 +2351,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSubscriptionsRequest() + new protos.google.pubsub.v1.ListSubscriptionsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSubscriptionsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSubscriptions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -2373,14 +2375,14 @@ describe('v1.SubscriberClient', () => { ( client.descriptors.page.listSubscriptions.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listSubscriptions.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); }); @@ -2391,16 +2393,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), @@ -2424,16 +2426,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), @@ -2446,14 +2448,14 @@ describe('v1.SubscriberClient', () => { request, ( err?: Error | null, - result?: protos.google.pubsub.v1.ISnapshot[] | null + result?: protos.google.pubsub.v1.ISnapshot[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2473,20 +2475,20 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listSnapshots = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(client.listSnapshots(request), expectedError); const actualRequest = ( @@ -2504,16 +2506,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), @@ -2539,14 +2541,14 @@ describe('v1.SubscriberClient', () => { assert( (client.descriptors.page.listSnapshots.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSnapshots, request) + .calledWith(client.innerApiCalls.listSnapshots, request), ); assert( (client.descriptors.page.listSnapshots.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -2555,16 +2557,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSnapshots.createStream = stubPageStreamingCall(undefined, expectedError); @@ -2585,14 +2587,14 @@ describe('v1.SubscriberClient', () => { assert( (client.descriptors.page.listSnapshots.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listSnapshots, request) + .calledWith(client.innerApiCalls.listSnapshots, request), ); assert( (client.descriptors.page.listSnapshots.createStream as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -2601,16 +2603,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), generateSampleMessage(new protos.google.pubsub.v1.Snapshot()), @@ -2628,14 +2630,14 @@ describe('v1.SubscriberClient', () => { ( client.descriptors.page.listSnapshots.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listSnapshots.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); @@ -2644,16 +2646,16 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new protos.google.pubsub.v1.ListSnapshotsRequest() + new protos.google.pubsub.v1.ListSnapshotsRequest(), ); const defaultValue1 = getTypeDefaultValue( '.google.pubsub.v1.ListSnapshotsRequest', - ['project'] + ['project'], ); request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1}`; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSnapshots.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -2668,14 +2670,14 @@ describe('v1.SubscriberClient', () => { ( client.descriptors.page.listSnapshots.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert( (client.descriptors.page.listSnapshots.asyncIterate as SinonStub) .getCall(0) .args[2].otherArgs.headers[ 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) + ].includes(expectedHeaderRequestParams), ); }); }); @@ -2685,9 +2687,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2699,7 +2701,7 @@ describe('v1.SubscriberClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); const response = await client.getIamPolicy(request, expectedOptions); @@ -2707,7 +2709,7 @@ describe('v1.SubscriberClient', () => { assert( (client.iamClient.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes getIamPolicy without error using callback', async () => { @@ -2715,9 +2717,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2729,25 +2731,25 @@ describe('v1.SubscriberClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.getIamPolicy = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.getIamPolicy( + void client.getIamPolicy( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.Policy | null + result?: IamProtos.google.iam.v1.Policy | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2759,9 +2761,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() + new IamProtos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2776,12 +2778,12 @@ describe('v1.SubscriberClient', () => { client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); await assert.rejects( client.getIamPolicy(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -2791,9 +2793,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2805,7 +2807,7 @@ describe('v1.SubscriberClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); const response = await client.setIamPolicy(request, expectedOptions); @@ -2813,7 +2815,7 @@ describe('v1.SubscriberClient', () => { assert( (client.iamClient.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes setIamPolicy without error using callback', async () => { @@ -2821,9 +2823,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2835,25 +2837,25 @@ describe('v1.SubscriberClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() + new IamProtos.google.iam.v1.Policy(), ); client.iamClient.setIamPolicy = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.setIamPolicy( + void client.setIamPolicy( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.Policy | null + result?: IamProtos.google.iam.v1.Policy | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2865,9 +2867,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() + new IamProtos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2882,12 +2884,12 @@ describe('v1.SubscriberClient', () => { client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); await assert.rejects( client.setIamPolicy(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -2897,9 +2899,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2911,18 +2913,18 @@ describe('v1.SubscriberClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), ); client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); const response = await client.testIamPermissions( request, - expectedOptions + expectedOptions, ); assert.deepStrictEqual(response, [expectedResponse]); assert( (client.iamClient.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes testIamPermissions without error using callback', async () => { @@ -2930,9 +2932,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2944,25 +2946,25 @@ describe('v1.SubscriberClient', () => { }, }; const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), ); client.iamClient.testIamPermissions = sinon .stub() .callsArgWith(2, null, expectedResponse); const promise = new Promise((resolve, reject) => { - client.testIamPermissions( + void client.testIamPermissions( request, expectedOptions, ( err?: Error | null, - result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -2974,9 +2976,9 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -2990,22 +2992,22 @@ describe('v1.SubscriberClient', () => { const expectedError = new Error('expected'); client.iamClient.testIamPermissions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.testIamPermissions(request, expectedOptions), - expectedError + expectedError, ); assert( (client.iamClient.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); describe('Path templates', () => { - describe('project', () => { + describe('project', async () => { const fakePath = '/rendered/path/project'; const expectedParameters = { project: 'projectValue', @@ -3014,7 +3016,7 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3028,7 +3030,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.projectPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -3038,12 +3040,12 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.projectPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('projectTopic', () => { + describe('projectTopic', async () => { const fakePath = '/rendered/path/projectTopic'; const expectedParameters = { project: 'projectValue', @@ -3053,7 +3055,7 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectTopicPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3067,7 +3069,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -3077,7 +3079,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -3087,12 +3089,12 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.projectTopicPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('schema', () => { + describe('schema', async () => { const fakePath = '/rendered/path/schema'; const expectedParameters = { project: 'projectValue', @@ -3102,7 +3104,7 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.schemaPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3116,7 +3118,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.schemaPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -3126,7 +3128,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.schemaPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -3136,12 +3138,12 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.schemaPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('snapshot', () => { + describe('snapshot', async () => { const fakePath = '/rendered/path/snapshot'; const expectedParameters = { project: 'projectValue', @@ -3151,7 +3153,7 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.snapshotPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3165,7 +3167,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -3175,7 +3177,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -3185,12 +3187,12 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.snapshotPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); - describe('subscription', () => { + describe('subscription', async () => { const fakePath = '/rendered/path/subscription'; const expectedParameters = { project: 'projectValue', @@ -3200,7 +3202,7 @@ describe('v1.SubscriberClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.subscriptionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3211,13 +3213,13 @@ describe('v1.SubscriberClient', () => { it('subscriptionPath', () => { const result = client.subscriptionPath( 'projectValue', - 'subscriptionValue' + 'subscriptionValue', ); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.subscriptionPathTemplate.render as SinonStub) .getCall(-1) - .calledWith(expectedParameters) + .calledWith(expectedParameters), ); }); @@ -3227,7 +3229,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.subscriptionPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); @@ -3237,7 +3239,7 @@ describe('v1.SubscriberClient', () => { assert( (client.pathTemplates.subscriptionPathTemplate.match as SinonStub) .getCall(-1) - .calledWith(fakePath) + .calledWith(fakePath), ); }); }); diff --git a/test/iam.ts b/test/iam.ts index d5f5763e2..a1f73f8bf 100644 --- a/test/iam.ts +++ b/test/iam.ts @@ -25,7 +25,7 @@ const fakeUtil = Object.assign({}, util, { promisifySome( class_: Function, classProtos: object, - methods: string[] + methods: string[], ): void { if (class_.name === 'IAM') { promisified = true; diff --git a/test/lease-manager.ts b/test/lease-manager.ts index ca26a4be0..c95b633f9 100644 --- a/test/lease-manager.ts +++ b/test/lease-manager.ts @@ -30,6 +30,8 @@ import { Subscriber, } from '../src/subscriber'; import {defaultOptions} from '../src/default-options'; +import {TestUtils} from './test-utils'; +import {Duration} from '../src'; const FREE_MEM = 9376387072; const fakeos = { @@ -40,6 +42,7 @@ class FakeSubscriber extends EventEmitter { ackDeadline = 10; isOpen = true; modAckLatency = 2000; + maxExtensionTime = Duration.from({minutes: 60}); async modAck(): Promise {} async modAckWithResponse(): Promise { return AckResponses.Success; @@ -237,7 +240,7 @@ describe('LeaseManager', () => { // This random number was generated once to keep the test results stable. random = 0.5756015072052962; sandbox.stub(global.Math, 'random').returns(random); - clock = sandbox.useFakeTimers(); + clock = TestUtils.useFakeTimers(sandbox); expectedTimeout = (subscriber.ackDeadline * 1000 * 0.9 - subscriber.modAckLatency) * random; @@ -285,33 +288,15 @@ describe('LeaseManager', () => { }); }); - it('should properly convert any legacy maxExtension values', () => { - const maxExtension = 60 * 1000; - leaseManager.setOptions({maxExtension}); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const options = (leaseManager as any)._options; - assert.strictEqual(options.maxExtensionMinutes, maxExtension / 60); - assert.strictEqual(options.maxExtension, undefined); - }); - - it('should not allow both maxExtension and maxExtensionMinutes', () => { - assert.throws(() => { - leaseManager.setOptions({ - maxExtension: 10, - maxExtensionMinutes: 10, - }); - }); - }); - it('should remove any messages that pass the maxExtensionMinutes value', () => { const maxExtensionSeconds = (expectedTimeout - 100) / 1000; const badMessages = [new FakeMessage(), new FakeMessage()]; - leaseManager.setOptions({ - maxExtensionMinutes: maxExtensionSeconds / 60, + subscriber.maxExtensionTime = Duration.from({ + seconds: maxExtensionSeconds, }); badMessages.forEach(message => - leaseManager.add(message as {} as Message) + leaseManager.add(message as {} as Message), ); clock.tick(halfway); @@ -338,9 +323,7 @@ describe('LeaseManager', () => { it('should remove and ackFailed any messages that fail to ack', done => { (subscriber as unknown as FakeSubscriber).isExactlyOnceDelivery = true; - leaseManager.setOptions({ - maxExtensionMinutes: 600, - }); + subscriber.maxExtensionTime = Duration.from({minutes: 600}); const goodMessage = new FakeMessage(); @@ -397,7 +380,7 @@ describe('LeaseManager', () => { }); it('should cancel any lease extensions', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const stub = sandbox.stub(subscriber, 'modAck').resolves(); leaseManager.add(new FakeMessage() as {} as Message); @@ -518,7 +501,7 @@ describe('LeaseManager', () => { }); it('should cancel any extensions if no messages are left', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const message = new FakeMessage() as {} as Message; const stub = sandbox.stub(subscriber, 'modAck').resolves(); @@ -563,7 +546,7 @@ describe('LeaseManager', () => { describe('deadline extension', () => { beforeEach(() => { - sandbox.useFakeTimers(); + TestUtils.useFakeTimers(sandbox); }); afterEach(() => { sandbox.clock.restore(); diff --git a/test/message-queues.ts b/test/message-queues.ts index b5d42b768..7dc31779a 100644 --- a/test/message-queues.ts +++ b/test/message-queues.ts @@ -26,13 +26,14 @@ import * as messageTypes from '../src/message-queues'; import {BatchError} from '../src/message-queues'; import {Message, Subscriber} from '../src/subscriber'; import {DebugMessage} from '../src/debug'; +import {TestUtils} from './test-utils'; class FakeClient { async acknowledge( // eslint-disable-next-line @typescript-eslint/no-unused-vars reqOpts: {subscription: string; ackIds: string[]}, // eslint-disable-next-line @typescript-eslint/no-unused-vars - callOptions: CallOptions + callOptions: CallOptions, ): Promise {} async modifyAckDeadline( // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -42,7 +43,7 @@ class FakeClient { ackDeadlineSeconds: number; }, // eslint-disable-next-line @typescript-eslint/no-unused-vars - callOptions: CallOptions + callOptions: CallOptions, ): Promise {} } @@ -80,7 +81,7 @@ function fakeMessage() { class MessageQueue extends messageTypes.MessageQueue { batches: messageTypes.QueuedMessages[] = []; async _sendBatch( - batch: messageTypes.QueuedMessages + batch: messageTypes.QueuedMessages, ): Promise { this.batches.push(batch); return []; @@ -147,7 +148,7 @@ describe('MessageQueues', () => { describe('add', () => { it('should increase the number of pending requests', () => { - messageQueue.add(new FakeMessage() as Message); + void messageQueue.add(new FakeMessage() as Message); assert.strictEqual(messageQueue.numPendingRequests, 1); }); @@ -155,7 +156,7 @@ describe('MessageQueues', () => { const stub = sandbox.stub(messageQueue, 'flush'); messageQueue.setOptions({maxMessages: 1}); - messageQueue.add(new FakeMessage() as Message); + void messageQueue.add(new FakeMessage() as Message); assert.strictEqual(stub.callCount, 1); }); @@ -164,18 +165,18 @@ describe('MessageQueues', () => { const stub = sandbox.stub(messageQueue, 'flush'); messageQueue.bytes = messageTypes.MAX_BATCH_BYTES - 10; - messageQueue.add(new FakeMessage() as Message); + void messageQueue.add(new FakeMessage() as Message); assert.strictEqual(stub.callCount, 1); }); it('should schedule a flush if needed', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const stub = sandbox.stub(messageQueue, 'flush'); const delay = 1000; messageQueue.setOptions({maxMilliseconds: delay}); - messageQueue.add(new FakeMessage() as Message); + void messageQueue.add(new FakeMessage() as Message); assert.strictEqual(stub.callCount, 0); clock.tick(delay); @@ -183,7 +184,7 @@ describe('MessageQueues', () => { }); it('should return a Promise that resolves when the ack is sent', async () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const delay = 1000; messageQueue.setOptions({maxMilliseconds: delay}); @@ -204,28 +205,28 @@ describe('MessageQueues', () => { describe('flush', () => { it('should cancel scheduled flushes', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const spy = sandbox.spy(messageQueue, 'flush'); const delay = 1000; messageQueue.setOptions({maxMilliseconds: delay}); - messageQueue.add(new FakeMessage() as Message); - messageQueue.flush(); + void messageQueue.add(new FakeMessage() as Message); + void messageQueue.flush(); clock.tick(delay); assert.strictEqual(spy.callCount, 1); }); it('should remove the messages from the queue', () => { - messageQueue.add(new FakeMessage() as Message); - messageQueue.flush(); + void messageQueue.add(new FakeMessage() as Message); + void messageQueue.flush(); assert.strictEqual(messageQueue.numPendingRequests, 0); }); it('should remove the bytes of messages from the queue', () => { - messageQueue.add(new FakeMessage() as Message); - messageQueue.flush(); + void messageQueue.add(new FakeMessage() as Message); + void messageQueue.flush(); assert.strictEqual(messageQueue.bytes, 0); }); @@ -234,8 +235,8 @@ describe('MessageQueues', () => { const message = new FakeMessage(); const deadline = 10; - messageQueue.add(message as Message, deadline); - messageQueue.flush(); + void messageQueue.add(message as Message, deadline); + void messageQueue.flush(); const [batch] = messageQueue.batches; assert.strictEqual(batch[0].message.ackId, message.ackId); @@ -253,12 +254,12 @@ describe('MessageQueues', () => { done(); }); - messageQueue.flush(); + void messageQueue.flush(); }); - it('should resolve any pending promises', () => { + it('should resolve any pending promises', async () => { const promise = messageQueue.onFlush(); - setImmediate(() => messageQueue.flush()); + setImmediate(async () => await messageQueue.flush()); return promise; }); @@ -277,8 +278,8 @@ describe('MessageQueues', () => { const onDrainBeforeFlush = messageQueue .onDrain() .then(() => log.push('drain1')); - messageQueue.add(message as Message, deadline); - messageQueue.flush(); + void messageQueue.add(message as Message, deadline); + void messageQueue.flush(); assert.deepStrictEqual(log, ['send:start']); sendDone.resolve(); await messageQueue.onDrain().then(() => log.push('drain2')); @@ -329,7 +330,7 @@ describe('MessageQueues', () => { for (let i = 0; i < 3000; i++) { assert.strictEqual(stub.callCount, 0); - messageQueue.add(fakeMessage()); + void messageQueue.add(fakeMessage()); } assert.strictEqual(stub.callCount, 1); @@ -343,29 +344,29 @@ describe('MessageQueues', () => { for (let i = 0; i < maxMessages; i++) { assert.strictEqual(stub.callCount, 0); - messageQueue.add(fakeMessage()); + void messageQueue.add(fakeMessage()); } assert.strictEqual(stub.callCount, 1); }); it('should default maxMilliseconds to 100', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const stub = sandbox.stub(messageQueue, 'flush'); - messageQueue.add(fakeMessage()); + void messageQueue.add(fakeMessage()); clock.tick(100); assert.strictEqual(stub.callCount, 1); }); it('should respect user supplied maxMilliseconds', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const stub = sandbox.stub(messageQueue, 'flush'); const maxMilliseconds = 10000; messageQueue.setOptions({maxMilliseconds}); - messageQueue.add(fakeMessage()); + void messageQueue.add(fakeMessage()); clock.tick(maxMilliseconds); assert.strictEqual(stub.callCount, 1); @@ -448,7 +449,7 @@ describe('MessageQueues', () => { }); messages.forEach(message => ackQueue.add(message as Message)); - ackQueue.flush(); + void ackQueue.flush(); }); // The analogous modAck version is very similar, so please sync changes. @@ -481,7 +482,7 @@ describe('MessageQueues', () => { sandbox.stub(fakeSubscriber.client, 'acknowledge').resolves(); const proms = ackQueue.requests.map( - (r: messageTypes.QueuedMessage) => r.responsePromise!.promise + (r: messageTypes.QueuedMessage) => r.responsePromise!.promise, ); await ackQueue.flush(); const results = await Promise.allSettled(proms); @@ -503,9 +504,9 @@ describe('MessageQueues', () => { sandbox.stub(fakeSubscriber.client, 'acknowledge').rejects(fakeError); const proms = ackQueue.requests.map( - (r: messageTypes.QueuedMessage) => r.responsePromise!.promise + (r: messageTypes.QueuedMessage) => r.responsePromise!.promise, ); - proms.shift(); + void proms.shift(); await ackQueue.flush(); const results = await Promise.allSettled(proms); @@ -557,7 +558,7 @@ describe('MessageQueues', () => { // This doesn't need to be duplicated down to modAck because it's just // testing common code. it('should retry transient failures', async () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); sandbox.stub(global.Math, 'random').returns(0.5); const message = fakeMessage(); @@ -569,7 +570,7 @@ describe('MessageQueues', () => { }; sandbox.stub(fakeSubscriber.client, 'acknowledge').rejects(fakeError); - ackQueue.add(message); + void ackQueue.add(message); await ackQueue.flush(); // Make sure the one handled by errorInfo was retried. @@ -636,7 +637,7 @@ describe('MessageQueues', () => { }; messages.forEach(message => - modAckQueue.add(message as Message, deadline) + modAckQueue.add(message as Message, deadline), ); await modAckQueue.flush(); @@ -676,10 +677,10 @@ describe('MessageQueues', () => { }; messages1.forEach(message => - modAckQueue.add(message as Message, deadline1) + modAckQueue.add(message as Message, deadline1), ); messages2.forEach(message => - modAckQueue.add(message as Message, deadline2) + modAckQueue.add(message as Message, deadline2), ); await modAckQueue.flush(); @@ -697,7 +698,7 @@ describe('MessageQueues', () => { .resolves(); modAckQueue.setOptions({callOptions: fakeCallOptions}); - modAckQueue.add(new FakeMessage() as Message, 10); + await modAckQueue.add(new FakeMessage() as Message, 10); await modAckQueue.flush(); const [, callOptions] = stub.lastCall.args; @@ -740,7 +741,7 @@ describe('MessageQueues', () => { }); messages.forEach(message => modAckQueue.add(message as Message)); - modAckQueue.flush(); + void modAckQueue.flush(); }); describe('handle modAck responses when !isExactlyOnceDelivery', () => { @@ -772,7 +773,7 @@ describe('MessageQueues', () => { sandbox.stub(fakeSubscriber.client, 'modifyAckDeadline').resolves(); const proms = modAckQueue.requests.map( - (r: messageTypes.QueuedMessage) => r.responsePromise!.promise + (r: messageTypes.QueuedMessage) => r.responsePromise!.promise, ); await modAckQueue.flush(); const results = await Promise.allSettled(proms); @@ -796,9 +797,9 @@ describe('MessageQueues', () => { .stub(fakeSubscriber.client, 'modifyAckDeadline') .rejects(fakeError); const proms = modAckQueue.requests.map( - (r: messageTypes.QueuedMessage) => r.responsePromise!.promise + (r: messageTypes.QueuedMessage) => r.responsePromise!.promise, ); - proms.shift(); + void proms.shift(); await modAckQueue.flush(); const results = await Promise.allSettled(proms); diff --git a/test/message-stream.ts b/test/message-stream.ts index 494083d5a..2463d17eb 100644 --- a/test/message-stream.ts +++ b/test/message-stream.ts @@ -22,12 +22,13 @@ import * as sinon from 'sinon'; import {Duplex, PassThrough} from 'stream'; import * as uuid from 'uuid'; import * as defer from 'p-defer'; +import {promisify} from 'util'; import * as messageTypes from '../src/message-stream'; import {Subscriber} from '../src/subscriber'; import {defaultOptions} from '../src/default-options'; import {Duration} from '../src/temporal'; -import {promisify} from 'util'; +import {TestUtils} from './test-utils'; const FAKE_STREAMING_PULL_TIMEOUT = 123456789; const FAKE_CLIENT_CONFIG = { @@ -63,13 +64,21 @@ class FakePassThrough extends PassThrough { } } +interface AccessReadableState { + _readableState: StreamState; +} + class FakeGrpcStream extends Duplex { options: StreamingPullOptions; - _readableState!: StreamState; constructor(options: StreamingPullOptions) { super({objectMode: true}); this.options = options; } + + get readableState(): StreamState { + return (this as unknown as AccessReadableState)._readableState; + } + cancel(): void { const status = { code: 1, @@ -156,8 +165,8 @@ describe('MessageStream', () => { }); beforeEach(async () => { - sandbox.useFakeTimers(); now = Date.now(); + TestUtils.useFakeTimers(sandbox, now); const gaxClient = new FakeGaxClient(); client = gaxClient.client; // we hit the grpc client directly @@ -180,7 +189,7 @@ describe('MessageStream', () => { }; assert.deepStrictEqual( (messageStream as {} as FakePassThrough).options, - expectedOptions + expectedOptions, ); }); @@ -195,7 +204,7 @@ describe('MessageStream', () => { assert.deepStrictEqual( (ms as {} as FakePassThrough).options, - expectedOptions + expectedOptions, ); }); @@ -207,14 +216,14 @@ describe('MessageStream', () => { describe('defaults', () => { it('should default highWaterMark to 0', () => { client.streams.forEach(stream => { - assert.strictEqual(stream._readableState.highWaterMark, 0); + assert.strictEqual(stream.readableState.highWaterMark, 0); }); }); it('should default maxStreams', () => { assert.strictEqual( client.streams.length, - defaultOptions.subscription.maxStreams + defaultOptions.subscription.maxStreams, ); }); @@ -229,7 +238,10 @@ describe('MessageStream', () => { it('should default timeout to 5 minutes', () => { const expectedTimeout = now + 60000 * 5; - assert.strictEqual(client.deadline, expectedTimeout); + + // Floating point calcuations in Duration might make this a few + // microseconds off. + assert.ok(Math.abs(client.deadline! - expectedTimeout) < 10); }); }); @@ -250,12 +262,13 @@ describe('MessageStream', () => { assert.strictEqual( client.streams.length, - defaultOptions.subscription.maxStreams + defaultOptions.subscription.maxStreams, ); + client.streams.forEach(stream => { assert.strictEqual( - stream._readableState.highWaterMark, - highWaterMark + stream.readableState.highWaterMark, + highWaterMark, ); }); }); diff --git a/test/publisher/flow-publisher.ts b/test/publisher/flow-publisher.ts index c4c0ed6d4..0ca59e567 100644 --- a/test/publisher/flow-publisher.ts +++ b/test/publisher/flow-publisher.ts @@ -60,17 +60,17 @@ describe('Flow control publisher', () => { parentSpan: tracing.PubsubSpans.createPublisherSpan( {}, 'projects/foo/topics/topic', - 'tests' + 'tests', ), }; - fcp.publish(message as unknown as PubsubMessage); + await fcp.publish(message as unknown as PubsubMessage); assert.strictEqual(!!message.parentSpan, true); }); it('should not create a flow span if no parent exists', async () => { const fcp = new fp.FlowControlledPublisher(publisher); const message = {data: Buffer.from('foo'), parentSpan: undefined}; - fcp.publish(message as unknown as PubsubMessage); + await fcp.publish(message as unknown as PubsubMessage); assert.strictEqual(!message.parentSpan, true); }); diff --git a/test/publisher/index.ts b/test/publisher/index.ts index 9393b470f..af693c65e 100644 --- a/test/publisher/index.ts +++ b/test/publisher/index.ts @@ -38,7 +38,7 @@ const fakeUtil = Object.assign({}, util, { class_: Function, classProtos: object, methods: string[], - options: pfy.PromisifyAllOptions + options: pfy.PromisifyAllOptions, ): void { if (class_.name === 'Publisher') { promisified = true; @@ -70,7 +70,7 @@ class FakeQueue extends EventEmitter { // eslint-disable-next-line @typescript-eslint/no-unused-vars messages: p.PubsubMessage[], // eslint-disable-next-line @typescript-eslint/no-unused-vars - callbacks: p.PublishCallback[] + callbacks: p.PublishCallback[], ) {} } @@ -92,7 +92,7 @@ class FakeOrderedQueue extends FakeQueue { // eslint-disable-next-line @typescript-eslint/no-unused-vars messages: p.PubsubMessage[], // eslint-disable-next-line @typescript-eslint/no-unused-vars - callbacks: p.PublishCallback[] + callbacks: p.PublishCallback[], ) {} } @@ -193,13 +193,13 @@ describe('Publisher', () => { exporter.reset(); }); - it('export created spans', async () => { + it('export created spans', () => { tracing.setGloballyEnabled(true); // Setup trace exporting tracingPublisher = new Publisher(topic); const msg = {data: buffer} as p.PubsubMessage; - tracingPublisher.publishMessage(msg); + void tracingPublisher.publishMessage(msg); // publishMessage is only the first part of the process now, // so we need to manually end the span. @@ -210,21 +210,21 @@ describe('Publisher', () => { const createdSpan = spans.concat().pop()!; assert.strictEqual( createdSpan.status.code, - opentelemetry.SpanStatusCode.UNSET + opentelemetry.SpanStatusCode.UNSET, ); assert.strictEqual( createdSpan.attributes['messaging.system'], - 'gcp_pubsub' + 'gcp_pubsub', ); assert.strictEqual( createdSpan.attributes['messaging.destination.name'], - topicId + topicId, ); assert.strictEqual(createdSpan.name, `${topicId} create`); assert.strictEqual( createdSpan.kind, SpanKind.PRODUCER, - 'span kind should be PRODUCER' + 'span kind should be PRODUCER', ); assert.ok(spans); }); @@ -237,14 +237,14 @@ describe('Publisher', () => { const badData = {} as Buffer; assert.throws( () => publisher.publishMessage({data: badData}, spy), - /Data must be in the form of a Buffer or Uint8Array\./ + /Data must be in the form of a Buffer or Uint8Array\./, ); }); it('should throw an error if data and attributes are both empty', () => { assert.throws( () => publisher.publishMessage({}, spy), - /at least one attribute must be present/ + /at least one attribute must be present/, ); }); @@ -258,7 +258,7 @@ describe('Publisher', () => { assert.throws( () => publisher.publishMessage({data, attributes}, spy), - /All attributes must be in the form of a string.\n\nInvalid value of type "object" provided for "foo"\./ + /All attributes must be in the form of a string.\n\nInvalid value of type "object" provided for "foo"\./, ); }); @@ -286,7 +286,7 @@ describe('Publisher', () => { queue = new FakeOrderedQueue(publisher, orderingKey); publisher.orderedQueues.set( orderingKey, - queue as unknown as q.OrderedQueue + queue as unknown as q.OrderedQueue, ); }); @@ -295,7 +295,7 @@ describe('Publisher', () => { publisher.publishMessage(fakeMessage, spy); queue = publisher.orderedQueues.get( - orderingKey + orderingKey, ) as unknown as FakeOrderedQueue; assert(queue instanceof FakeOrderedQueue); @@ -335,7 +335,7 @@ describe('Publisher', () => { publisher.publishMessage(fakeMessage, spy); queue = publisher.orderedQueues.get( - orderingKey + orderingKey, ) as unknown as FakeOrderedQueue; queue.emit('drain'); @@ -356,7 +356,7 @@ describe('Publisher', () => { .stub(FakeOrderedQueue.prototype, '_publish') .callsFake(async () => { const queue = publisher.orderedQueues.get( - orderingKey + orderingKey, ) as unknown as FakeOrderedQueue; // Simulate the drain taking longer than the publishes. This can // happen on some ordered queue scenarios, especially if we have more @@ -375,22 +375,6 @@ describe('Publisher', () => { done(); }); }); - - it('should issue a warning if OpenTelemetry span context key is set', () => { - tracing.setGloballyEnabled(true); - - const warnSpy = sinon.spy(console, 'warn'); - const attributes = { - [tracing.legacyAttributeName]: 'foobar', - }; - const fakeMessageWithOTKey = {data, attributes}; - const publisherTracing = new Publisher(topic, { - enableOpenTelemetryTracing: true, - }); - publisherTracing.publishMessage(fakeMessageWithOTKey, warnSpy); - assert.ok(warnSpy.called); - warnSpy.restore(); - }); }); }); @@ -402,7 +386,7 @@ describe('Publisher', () => { publisher.orderedQueues.set( orderingKey, - queue as unknown as q.OrderedQueue + queue as unknown as q.OrderedQueue, ); publisher.resumePublishing(orderingKey); @@ -424,7 +408,6 @@ describe('Publisher', () => { gaxOpts: { isBundling: false, }, - enableOpenTelemetryTracing: false, flowControlOptions: { maxOutstandingBytes: undefined, maxOutstandingMessages: undefined, @@ -443,7 +426,6 @@ describe('Publisher', () => { gaxOpts: { isBundling: true, }, - enableOpenTelemetryTracing: true, flowControlOptions: { maxOutstandingBytes: 500, maxOutstandingMessages: 50, @@ -484,8 +466,8 @@ describe('Publisher', () => { assert.deepStrictEqual(publisher.orderedQueues.size, 2); stubs.push( ...Array.from(publisher.orderedQueues.values()).map(q => - sandbox.stub(q, 'updateOptions') - ) + sandbox.stub(q, 'updateOptions'), + ), ); const newOptions: p.PublishOptions = { @@ -512,7 +494,7 @@ describe('Publisher', () => { assert.strictEqual(err, null); assert.strictEqual( !publisher.queue.batch || publisher.queue.batch.messages.length === 0, - true + true, ); done(); }); diff --git a/test/publisher/message-queues.ts b/test/publisher/message-queues.ts index b9cefea53..873e61c0e 100644 --- a/test/publisher/message-queues.ts +++ b/test/publisher/message-queues.ts @@ -26,6 +26,7 @@ import * as p from '../../src/publisher'; import * as b from '../../src/publisher/message-batch'; import * as q from '../../src/publisher/message-queues'; import {PublishError} from '../../src/publisher/publish-error'; +import {TestUtils} from '../test-utils'; class FakeTopic { name = 'projects/foo/topics/fake-topic'; @@ -158,7 +159,7 @@ describe('Message Queues', () => { it('should make the correct request', () => { const stub = sandbox.stub(topic, 'request'); - queue._publish(messages, callbacks); + void queue._publish(messages, callbacks); const [{client, method, reqOpts}] = stub.lastCall.args; assert.strictEqual(client, 'PublisherClient'); @@ -171,7 +172,7 @@ describe('Message Queues', () => { const callOptions = {}; publisher.settings.gaxOpts = callOptions; - queue._publish(messages, callbacks); + void queue._publish(messages, callbacks); const [{gaxOpts}] = stub.lastCall.args; assert.strictEqual(gaxOpts, callOptions); @@ -279,7 +280,7 @@ describe('Message Queues', () => { }); it('should set a timeout to publish if need be', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const stub = sandbox.stub(queue, 'publish').resolves(); const maxMilliseconds = 1234; @@ -293,7 +294,7 @@ describe('Message Queues', () => { }); it('should noop if a timeout is already set', () => { - const clock = sandbox.useFakeTimers(); + const clock = TestUtils.useFakeTimers(sandbox); const stub = sandbox.stub(queue, 'publish').resolves(); const maxMilliseconds = 1234; @@ -308,33 +309,33 @@ describe('Message Queues', () => { }); describe('publish', () => { - it('should create a new batch', () => { + it('should create a new batch', async () => { const oldBatch = queue.batch; - queue.publish(); + await queue.publish(); assert.notStrictEqual(oldBatch, queue.batch); assert.ok(queue.batch instanceof FakeMessageBatch); assert.strictEqual(queue.batch.options, queue.batchOptions); }); - it('should cancel any pending publish calls', () => { + it('should cancel any pending publish calls', async () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const fakeHandle = 1234 as unknown as any; const stub = sandbox.stub(global, 'clearTimeout').withArgs(fakeHandle); queue.pending = fakeHandle; - queue.publish(); + await queue.publish(); assert.strictEqual(stub.callCount, 1); assert.strictEqual(queue.pending, undefined); }); - it('should publish the messages', () => { + it('should publish the messages', async () => { const batch = queue.batch; const stub = sandbox.stub(queue, '_publish'); - queue.publish(); + await queue.publish(); const [messages, callbacks] = stub.lastCall.args; assert.strictEqual(messages, batch.messages); @@ -366,7 +367,7 @@ describe('Message Queues', () => { queue.batch = new FakeMessageBatch(); queue.batch.messages = fakeMessages; queue.batch.callbacks = spies; - queue.publishDrain().then(() => { + void queue.publishDrain().then(() => { process.nextTick(() => { assert.strictEqual(stub.callCount, 2); done(); @@ -374,7 +375,7 @@ describe('Message Queues', () => { }); }); - it('should not begin another publish(non-drain) if there are pending batches', () => { + it('should not begin another publish(non-drain) if there are pending batches', async () => { const stub = sandbox.stub(queue, '_publish'); let once = false; stub.callsFake(async () => { @@ -391,9 +392,9 @@ describe('Message Queues', () => { queue.batch = new FakeMessageBatch(); queue.batch.messages = fakeMessages; queue.batch.callbacks = spies; - queue.publish().then(() => { - assert.strictEqual(stub.callCount, 1); - }); + await queue.publish(); + + assert.strictEqual(stub.callCount, 1); }); it('should emit "drain" if there is nothing left to publish', done => { @@ -401,7 +402,7 @@ describe('Message Queues', () => { sandbox.stub(queue, '_publish').callsFake(async () => {}); queue.on('drain', spy); - queue.publish().then(() => { + void queue.publish().then(() => { process.nextTick(() => { assert.strictEqual(spy.callCount, 1); done(); @@ -582,7 +583,7 @@ describe('Message Queues', () => { beforeEach(() => { queue.batchOptions = {maxMilliseconds}; - clock = sinon.useFakeTimers(); + clock = TestUtils.useFakeTimers(sandbox); }); afterEach(() => { @@ -660,7 +661,7 @@ describe('Message Queues', () => { }); it('should set inFlight to true', () => { - queue.publish(); + void queue.publish(); assert.strictEqual(queue.inFlight, true); }); @@ -669,7 +670,7 @@ describe('Message Queues', () => { const stub = sandbox.stub(global, 'clearTimeout'); queue.pending = fakeHandle; - queue.publish(); + void queue.publish(); const [handle] = stub.lastCall.args; assert.strictEqual(handle, fakeHandle); @@ -679,15 +680,15 @@ describe('Message Queues', () => { it('should remove the oldest batch from the batch list', () => { const oldestBatch = queue.currentBatch; - queue.publish(); + void queue.publish(); assert.notStrictEqual(queue.currentBatch, oldestBatch); }); - it('should publish the batch', () => { + it('should publish the batch', async () => { const stub = sandbox.stub(queue, '_publish'); - queue.publish(); + await queue.publish(); const [messages, callbacks] = stub.lastCall.args; assert.strictEqual(messages, fakeMessages); diff --git a/test/publisher/publish-error.ts b/test/publisher/publish-error.ts index 2d2cd71cd..f7502beb5 100644 --- a/test/publisher/publish-error.ts +++ b/test/publisher/publish-error.ts @@ -36,7 +36,7 @@ describe('PublishError', () => { it('should give a helpful message', () => { assert.strictEqual( error.message, - `Unable to publish for key "${orderingKey}". Reason: ${fakeError.message}` + `Unable to publish for key "${orderingKey}". Reason: ${fakeError.message}`, ); }); diff --git a/test/pubsub.ts b/test/pubsub.ts index d0dd97bcf..facc21629 100644 --- a/test/pubsub.ts +++ b/test/pubsub.ts @@ -43,7 +43,7 @@ let subscriptionOverride: any; function Subscription( pubsub: pubsubTypes.PubSub, name: string, - options: subby.SubscriptionOptions + options: subby.SubscriptionOptions, ) { const overrideFn = subscriptionOverride || subscriptionCached; return new overrideFn(pubsub, name, options); @@ -59,7 +59,7 @@ const fakeUtil = Object.assign({}, util, { promisifySome( class_: Function, classProtos: object, - methods: string[] + methods: string[], ): void { if (class_.name === 'PubSub') { promisified = true; @@ -312,7 +312,7 @@ describe('PubSub', () => { const pubsub = new PubSub(options); assert.strictEqual( tracing.isEnabled(), - tracing.OpenTelemetryLevel.Modern + tracing.OpenTelemetryLevel.Modern, ); }); @@ -356,6 +356,34 @@ describe('PubSub', () => { it('should set isEmulator to false by default', () => { assert.strictEqual(pubsub.isEmulator, false); }); + + describe('tracing', () => { + beforeEach(() => { + tracing.setGloballyEnabled(false); + }); + afterEach(() => { + tracing.setGloballyEnabled(false); + }); + it('should not enable OTel when tracing is disabled', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _pubsub = new PubSub({}); + assert.strictEqual( + tracing.isEnabled(), + tracing.OpenTelemetryLevel.None, + ); + }); + + it('should enable OTel when tracing is enabled through constructor', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _pubsub = new PubSub({ + enableOpenTelemetryTracing: true, + }); + assert.strictEqual( + tracing.isEnabled(), + tracing.OpenTelemetryLevel.Modern, + ); + }); + }); }); describe('createSubscription', () => { @@ -474,7 +502,7 @@ describe('PubSub', () => { const expectedBody = Object.assign( {topic: TOPIC.name, name: SUB_NAME}, - options + options, ); pubsub.topic = () => { @@ -549,7 +577,7 @@ describe('PubSub', () => { TOPIC, SUB_NAME, fakeMetadata, - assert.ifError + assert.ifError, ); }); @@ -571,7 +599,7 @@ describe('PubSub', () => { function callback( err?: Error | null, sub?: subby.Subscription | null, - resp?: google.pubsub.v1.ISubscription | null + resp?: google.pubsub.v1.ISubscription | null, ) { assert.strictEqual(err, error); assert.strictEqual(sub, null); @@ -607,7 +635,7 @@ describe('PubSub', () => { function callback( err?: Error | null, sub?: subby.Subscription | null, - resp?: google.pubsub.v1.ISubscription | null + resp?: google.pubsub.v1.ISubscription | null, ) { assert.ifError(err); assert.strictEqual(sub, subscription); @@ -631,7 +659,7 @@ describe('PubSub', () => { const [sub, resp] = await pubsub.createSubscription!( TOPIC_NAME, - SUB_NAME + SUB_NAME, )!; assert.strictEqual(sub.name.includes('{{'), false); assert.strictEqual(resp, apiResponse); @@ -1025,7 +1053,7 @@ describe('PubSub', () => { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); delete expectedOptions.gaxOpts; @@ -1057,7 +1085,7 @@ describe('PubSub', () => { assert.strictEqual( // eslint-disable-next-line @typescript-eslint/no-explicit-any (snapshots![0] as any).metadata, - apiResponse.snapshots[0] + apiResponse.snapshots[0], ); done(); }); @@ -1111,7 +1139,7 @@ describe('PubSub', () => { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); const project = 'projects/' + pubsub.projectId; @@ -1146,12 +1174,12 @@ describe('PubSub', () => { pubsub.getSubscriptions?.( ( err: gax.grpc.ServiceError | null, - subscriptions?: subby.Subscription[] | null + subscriptions?: subby.Subscription[] | null, ) => { assert.ifError(err); assert(subscriptions![0] instanceof subscriptionCached); done(); - } + }, ); }); @@ -1169,13 +1197,13 @@ describe('PubSub', () => { ( err: gax.grpc.ServiceError | null, subs?: subby.Subscription[] | null, - apiResponse?: google.pubsub.v1.IListSubscriptionsResponse | null + apiResponse?: google.pubsub.v1.IListSubscriptionsResponse | null, ) => { assert.strictEqual(err, err_); assert.deepStrictEqual(subs, subs_); assert.strictEqual(apiResponse, nextQuery_); done(); - } + }, ); }); @@ -1255,7 +1283,7 @@ describe('PubSub', () => { { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); delete expectedOptions.gaxOpts; @@ -1339,7 +1367,7 @@ describe('PubSub', () => { assert.notStrictEqual(errInner, null); assert.strictEqual( errInner!.message.indexOf('closed PubSub object') >= 0, - true + true, ); done(); }); @@ -1373,7 +1401,7 @@ describe('PubSub', () => { (fakeClient as any).fakeMethod = ( // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, - gaxOpts: gax.CallOptions + gaxOpts: gax.CallOptions, ) => { assert.deepStrictEqual(CONFIG.reqOpts, reqOpts); assert.deepStrictEqual(CONFIG.gaxOpts, gaxOpts); @@ -1501,7 +1529,7 @@ describe('PubSub', () => { it('should return the correct client', async () => { // tslint:disable-next-line only-arrow-functions no-any v1ClientOverrides.FakeClient = function ( - options: pubsubTypes.ClientConfig + options: pubsubTypes.ClientConfig, ) { assert.strictEqual(options, pubsub.options); return FAKE_CLIENT_INSTANCE; @@ -1663,7 +1691,7 @@ describe('PubSub', () => { // tslint:disable-next-line only-arrow-functions subscriptionOverride = function ( pubsub: pubsubTypes.PubSub, - name: string + name: string, ) { assert.strictEqual(name, SUB_NAME); done(); @@ -1676,7 +1704,7 @@ describe('PubSub', () => { subscriptionOverride = function ( pubsub: pubsubTypes.PubSub, name: string, - options: subby.SubscriptionOptions + options: subby.SubscriptionOptions, ) { assert.strictEqual(options, CONFIG); done(); diff --git a/test/pull-retry.ts b/test/pull-retry.ts index e5b2523d8..b2f6a7118 100644 --- a/test/pull-retry.ts +++ b/test/pull-retry.ts @@ -65,7 +65,7 @@ describe('PullRetry', () => { assert.ok( PullRetry.resetFailures({ code: grpc.status.OK, - } as grpc.StatusObject) + } as grpc.StatusObject), ); }); @@ -73,7 +73,7 @@ describe('PullRetry', () => { assert.ok( PullRetry.resetFailures({ code: grpc.status.DEADLINE_EXCEEDED, - } as grpc.StatusObject) + } as grpc.StatusObject), ); }); }); diff --git a/test/snapshot.ts b/test/snapshot.ts index 2ebe8865d..5e5da3efe 100644 --- a/test/snapshot.ts +++ b/test/snapshot.ts @@ -28,7 +28,7 @@ const fakeUtil = Object.assign({}, util, { promisifySome( class_: Function, classProtos: object, - methods: string[] + methods: string[], ): void { if (class_.name === 'Snapshot') { promisified = true; @@ -197,14 +197,14 @@ describe('Snapshot', () => { it('should throw on create method', async () => { await assert.rejects( () => snapshot.create(), - /This is only available if you accessed this object through Subscription#snapshot/ + /This is only available if you accessed this object through Subscription#snapshot/, ); }); it('should throw on seek method', async () => { await assert.rejects( () => snapshot.seek(), - /This is only available if you accessed this object through Subscription#snapshot/ + /This is only available if you accessed this object through Subscription#snapshot/, ); }); }); diff --git a/test/subscriber.ts b/test/subscriber.ts index 7ab85ab67..df95cc1b9 100644 --- a/test/subscriber.ts +++ b/test/subscriber.ts @@ -150,7 +150,7 @@ class FakeMessageStream extends PassThrough { // eslint-disable-next-line @typescript-eslint/no-unused-vars _error: Error | null, // eslint-disable-next-line @typescript-eslint/no-unused-vars - _callback: (error: Error | null) => void + _callback: (error: Error | null) => void, ): void {} async start() {} } @@ -234,9 +234,9 @@ describe('Subscriber', () => { subscriber.open(); }); - afterEach(() => { + afterEach(async () => { sandbox.restore(); - subscriber.close(); + await subscriber.close(); tracing.setGloballyEnabled(false); }); @@ -259,12 +259,14 @@ describe('Subscriber', () => { }); it('should set any options passed in', () => { - const stub = sandbox.stub(Subscriber.prototype, 'setOptions'); - const fakeOptions = {}; - new Subscriber(subscription, fakeOptions); - - const [options] = stub.lastCall.args; - assert.strictEqual(options, fakeOptions); + const options = { + streamingOptions: {}, + }; + const subscriber = new Subscriber(subscription, options); + assert.strictEqual( + subscriber.getOptions().streamingOptions, + options.streamingOptions, + ); }); }); @@ -410,7 +412,7 @@ describe('Subscriber', () => { }); describe('ack', () => { - it('should update the ack histogram/deadline', () => { + it('should update the ack histogram/deadline', async () => { const histogram: FakeHistogram = stubs.get('histogram'); const now = Date.now(); @@ -424,13 +426,13 @@ describe('Subscriber', () => { sandbox.stub(histogram, 'percentile').withArgs(99).returns(fakeDeadline); - subscriber.ack(message); + await subscriber.ack(message); assert.strictEqual(addStub.callCount, 1); assert.strictEqual(subscriber.ackDeadline, fakeDeadline); }); - it('should bound ack deadlines if min/max are specified', () => { + it('should bound ack deadlines if min/max are specified', async () => { const histogram: FakeHistogram = stubs.get('histogram'); const now = Date.now(); @@ -449,7 +451,7 @@ describe('Subscriber', () => { subscriber.setOptions({ maxAckDeadline: Duration.from({seconds: 60}), }); - subscriber.ack(message); + await subscriber.ack(message); assert.strictEqual(addStub.callCount, 1); assert.strictEqual(subscriber.ackDeadline, 60); @@ -458,13 +460,13 @@ describe('Subscriber', () => { minAckDeadline: Duration.from({seconds: 10}), }); fakeDeadline = 1; - subscriber.ack(message); + await subscriber.ack(message); assert.strictEqual(subscriber.ackDeadline, 10); }); - it('should default to 60s min for exactly-once delivery subscriptions', () => { - subscriber.subscriptionProperties = {exactlyOnceDeliveryEnabled: true}; + it('should default to 60s min for exactly-once delivery subscriptions', async () => { + subscriber.setSubscriptionProperties({exactlyOnceDeliveryEnabled: true}); const histogram: FakeHistogram = stubs.get('histogram'); const now = Date.now(); @@ -478,7 +480,7 @@ describe('Subscriber', () => { const fakeDeadline = 10; sandbox.stub(histogram, 'percentile').withArgs(99).returns(fakeDeadline); - subscriber.ack(message); + await subscriber.ack(message); assert.strictEqual(addStub.callCount, 1); assert.strictEqual(subscriber.ackDeadline, 60); @@ -487,7 +489,7 @@ describe('Subscriber', () => { subscriber.setOptions({ minAckDeadline: Duration.from({seconds: 5}), }); - subscriber.ack(message); + await subscriber.ack(message); assert.strictEqual(subscriber.ackDeadline, 10); }); @@ -501,11 +503,13 @@ describe('Subscriber', () => { sandbox.stub(histogram, 'add').throws(); sandbox.stub(histogram, 'percentile').throws(); + const deadlineTime = Duration.from({seconds: ackDeadline}); subscriber.setOptions({ - ackDeadline, + minAckDeadline: deadlineTime, + maxAckDeadline: deadlineTime, flowControl: {maxMessages: maxMessages, maxBytes: maxBytes}, }); - subscriber.ack(message); + void subscriber.ack(message); assert.strictEqual(subscriber.ackDeadline, ackDeadline); }); @@ -514,7 +518,7 @@ describe('Subscriber', () => { const ackQueue: FakeAckQueue = stubs.get('ackQueue'); const stub = sandbox.stub(ackQueue, 'add').withArgs(message); - subscriber.ack(message); + void subscriber.ack(message); assert.strictEqual(stub.callCount, 1); }); @@ -533,7 +537,7 @@ describe('Subscriber', () => { done(); }); - subscriber.ack(message); + void subscriber.ack(message); }); }); @@ -549,16 +553,16 @@ describe('Subscriber', () => { return s.close(); }); - it('should set isOpen to false', () => { - subscriber.close(); + it('should set isOpen to false', async () => { + await subscriber.close(); assert.strictEqual(subscriber.isOpen, false); }); - it('should destroy the message stream', () => { + it('should destroy the message stream', async () => { const stream: FakeMessageStream = stubs.get('messageStream'); const stub = sandbox.stub(stream, 'destroy'); - subscriber.close(); + await subscriber.close(); assert.strictEqual(stub.callCount, 1); }); @@ -575,16 +579,16 @@ describe('Subscriber', () => { it('should emit a close event', done => { subscriber.on('close', done); - subscriber.close(); + void subscriber.close(); }); - it('should nack any messages that come in after', () => { + it('should nack any messages that come in after', async () => { const stream: FakeMessageStream = stubs.get('messageStream'); const stub = sandbox.stub(subscriber, 'nack'); const shutdownStub = sandbox.stub(tracing.PubsubEvents, 'shutdown'); const pullResponse = {receivedMessages: [RECEIVED_MESSAGE]}; - subscriber.close(); + await subscriber.close(); stream.emit('data', pullResponse); const [{ackId}] = stub.lastCall.args; @@ -666,7 +670,7 @@ describe('Subscriber', () => { const modAckQueue: FakeModAckQueue = stubs.get('modAckQueue'); const stub = sandbox.stub(modAckQueue, 'add').withArgs(message, deadline); - subscriber.modAck(message, deadline); + void subscriber.modAck(message, deadline); assert.strictEqual(stub.callCount, 1); }); @@ -847,10 +851,13 @@ describe('Subscriber', () => { beforeEach(() => subscriber.close()); it('should capture the ackDeadline', () => { - const ackDeadline = 1232; + const ackDeadline = Duration.from({seconds: 1232}); - subscriber.setOptions({ackDeadline}); - assert.strictEqual(subscriber.ackDeadline, ackDeadline); + subscriber.setOptions({ + minAckDeadline: ackDeadline, + maxAckDeadline: ackDeadline, + }); + assert.strictEqual(subscriber.ackDeadline, ackDeadline.totalOf('second')); }); it('should not set maxStreams higher than maxMessages', () => { @@ -867,51 +874,22 @@ describe('Subscriber', () => { }); describe('OpenTelemetry tracing', () => { - const enableTracing: s.SubscriberOptions = { - enableOpenTelemetryTracing: true, - }; - const disableTracing: s.SubscriberOptions = { - enableOpenTelemetryTracing: false, - }; - beforeEach(() => { exporter.reset(); }); - afterEach(() => { + afterEach(async () => { + tracing.setGloballyEnabled(false); exporter.reset(); - subscriber.close(); - }); - - it('should not instantiate a tracer when tracing is disabled', () => { - subscriber = new Subscriber(subscription, {}); - assert.strictEqual(subscriber['_useLegacyOpenTelemetry'], false); - }); - - it('should instantiate a tracer when tracing is enabled through constructor', () => { - subscriber = new Subscriber(subscription, enableTracing); - assert.ok(subscriber['_useLegacyOpenTelemetry']); - }); - - it('should instantiate a tracer when tracing is enabled through setOptions', () => { - subscriber = new Subscriber(subscription, {}); - subscriber.setOptions(enableTracing); - assert.ok(subscriber['_useLegacyOpenTelemetry']); - }); - - it('should disable tracing when tracing is disabled through setOptions', () => { - subscriber = new Subscriber(subscription, enableTracing); - subscriber.setOptions(disableTracing); - assert.strictEqual(subscriber['_useLegacyOpenTelemetry'], false); + await subscriber.close(); }); it('exports a span once it is created', () => { tracing.setGloballyEnabled(true); subscription = new FakeSubscription() as {} as Subscription; - subscriber = new Subscriber(subscription, enableTracing); + subscriber = new Subscriber(subscription, {}); message = new Message(subscriber, RECEIVED_MESSAGE); - assert.strictEqual(subscriber['_useLegacyOpenTelemetry'], true); subscriber.open(); // Construct mock of received message with span context @@ -920,12 +898,14 @@ describe('Subscriber', () => { spanId: '6e0c63257de34c92', traceFlags: opentelemetry.TraceFlags.SAMPLED, }; + const parentSpan = opentelemetry.trace.getSpan( + tracing.spanContextToContext(parentSpanContext)!, + ); const messageWithSpanContext = { ackId: uuid.v4(), message: { attributes: { - googclient_OpenTelemetrySpanContext: - JSON.stringify(parentSpanContext), + [tracing.modernAttributeName]: JSON.stringify(parentSpanContext), }, data: Buffer.from('Hello, world!'), messageId: uuid.v4(), @@ -933,6 +913,7 @@ describe('Subscriber', () => { publishTime: {seconds: 12, nanos: 32}, }, }; + tracing.injectSpan(parentSpan!, messageWithSpanContext.message); const pullResponse: s.PullResponse = { receivedMessages: [messageWithSpanContext], }; @@ -957,19 +938,19 @@ describe('Subscriber', () => { assert.strictEqual( firstSpan.name, `${subId} subscribe`, - 'name of span should match' + 'name of span should match', ); assert.strictEqual( firstSpan.kind, SpanKind.CONSUMER, - 'span kind should be CONSUMER' + 'span kind should be CONSUMER', ); }); it('exports a span even when a span context is not present on message', () => { tracing.setGloballyEnabled(true); - subscriber = new Subscriber(subscription, enableTracing); + subscriber = new Subscriber(subscription, {}); subscriber.open(); const pullResponse: s.PullResponse = { @@ -999,7 +980,7 @@ describe('Subscriber', () => { it('should localize attributes', () => { assert.strictEqual( message.attributes, - RECEIVED_MESSAGE.message.attributes + RECEIVED_MESSAGE.message.attributes, ); }); @@ -1014,7 +995,7 @@ describe('Subscriber', () => { it('should localize orderingKey', () => { assert.strictEqual( message.orderingKey, - RECEIVED_MESSAGE.message.orderingKey + RECEIVED_MESSAGE.message.orderingKey, ); }); @@ -1025,7 +1006,7 @@ describe('Subscriber', () => { assert(timestamp instanceof FakePreciseDate); assert.strictEqual( timestamp.value, - RECEIVED_MESSAGE.message.publishTime + RECEIVED_MESSAGE.message.publishTime, ); }); diff --git a/test/subscription.ts b/test/subscription.ts index 77717f617..aee0a9f90 100644 --- a/test/subscription.ts +++ b/test/subscription.ts @@ -31,7 +31,7 @@ const fakeUtil = Object.assign({}, util, { promisifySome( class_: Function, classProtos: object, - methods: string[] + methods: string[], ): void { if (class_.name === 'Subscription') { promisified = true; @@ -254,7 +254,7 @@ describe('Subscription', () => { assert.strictEqual( formatted.messageRetentionDuration!.seconds, - threeDaysInSeconds + threeDaysInSeconds, ); }); @@ -270,7 +270,7 @@ describe('Subscription', () => { assert.strictEqual(formatted.pushConfig!.pushEndpoint, pushEndpoint); assert.strictEqual( (formatted as subby.SubscriptionMetadata).pushEndpoint, - undefined + undefined, ); }); @@ -289,7 +289,7 @@ describe('Subscription', () => { assert.strictEqual(formatted.pushConfig!.oidcToken, oidcToken); assert.strictEqual( (formatted as subby.SubscriptionMetadata).oidcToken, - undefined + undefined, ); }); @@ -311,13 +311,13 @@ describe('Subscription', () => { assert.strictEqual(formatted.pushConfig!.pushEndpoint, pushEndpoint); assert.strictEqual( (formatted as subby.SubscriptionMetadata).pushEndpoint, - undefined + undefined, ); assert.strictEqual(formatted.pushConfig!.oidcToken, oidcToken); assert.strictEqual( (formatted as subby.SubscriptionMetadata).oidcToken, - undefined + undefined, ); }); }); @@ -981,7 +981,7 @@ describe('Subscription', () => { { name: SUB_FULL_NAME, }, - formattedMetadata + formattedMetadata, ); Subscription.formatMetadata_ = metadata => { diff --git a/test/telemetry-tracing.ts b/test/telemetry-tracing.ts index d624a6146..2bff66e30 100644 --- a/test/telemetry-tracing.ts +++ b/test/telemetry-tracing.ts @@ -82,7 +82,7 @@ describe('OpenTelemetryTracer', () => { const span = otel.PubsubSpans.createPublisherSpan( message, 'projects/test/topics/topicfoo', - 'tests' + 'tests', ) as trace.Span; span.end(); @@ -101,78 +101,66 @@ describe('OpenTelemetryTracer', () => { const span = otel.PubsubSpans.createPublisherSpan( message, 'projects/test/topics/topicfoo', - 'tests' + 'tests', ) as trace.Span; - otel.injectSpan(span, message, otel.OpenTelemetryLevel.Modern); + otel.injectSpan(span, message); assert.strictEqual( Object.getOwnPropertyNames(message.attributes).includes( - otel.modernAttributeName + otel.modernAttributeName, ), - true + true, ); }); }); describe('context propagation', () => { - it('injects a trace context and legacy baggage', () => { + it('injects a trace context', () => { const message: PubsubMessage = { attributes: {}, }; const span = otel.PubsubSpans.createPublisherSpan( message, 'projects/test/topics/topicfoo', - 'tests' + 'tests', ); assert.ok(span); - otel.injectSpan(span, message, otel.OpenTelemetryLevel.Legacy); + otel.injectSpan(span, message); assert.strictEqual( Object.getOwnPropertyNames(message.attributes).includes( - otel.modernAttributeName - ), - true - ); - assert.strictEqual( - Object.getOwnPropertyNames(message.attributes).includes( - otel.legacyAttributeName + otel.modernAttributeName, ), - true + true, ); }); it('should issue a warning if OpenTelemetry span context key is set', () => { const message: PubsubMessage = { attributes: { - [otel.legacyAttributeName]: 'foobar', [otel.modernAttributeName]: 'bazbar', }, }; const span = otel.PubsubSpans.createPublisherSpan( message, 'projects/test/topics/topicfoo', - 'tests' + 'tests', ); assert.ok(span); const warnSpy = sinon.spy(console, 'warn'); try { - otel.injectSpan(span, message, otel.OpenTelemetryLevel.Legacy); - assert.strictEqual(warnSpy.callCount, 2); + otel.injectSpan(span, message); + assert.strictEqual(warnSpy.callCount, 1); } finally { warnSpy.restore(); } }); it('should be able to determine if attributes are present', () => { - let message: otel.MessageWithAttributes = { - attributes: { - [otel.legacyAttributeName]: 'foobar', - }, - }; - assert.strictEqual(otel.containsSpanContext(message), true); + let message: otel.MessageWithAttributes; message = { attributes: { @@ -196,11 +184,10 @@ describe('OpenTelemetryTracer', () => { const childSpan = otel.extractSpan( message, 'projects/test/subscriptions/subfoo', - otel.OpenTelemetryLevel.Modern ); assert.strictEqual( childSpan!.spanContext().traceId, - 'd4cda95b652f4a1592b449d5929fda1b' + 'd4cda95b652f4a1592b449d5929fda1b', ); }); }); @@ -224,7 +211,7 @@ describe('OpenTelemetryTracer', () => { const topicAttrs = otel.PubsubSpans.createAttributes( topicInfo, message, - 'tests' + 'tests', ); assert.deepStrictEqual(topicAttrs, { 'messaging.system': 'gcp_pubsub', @@ -247,7 +234,7 @@ describe('OpenTelemetryTracer', () => { const topicAttrs2 = otel.PubsubSpans.createAttributes( topicInfo, message, - 'tests' + 'tests', ); assert.deepStrictEqual(topicAttrs2, { 'messaging.system': 'gcp_pubsub', @@ -285,7 +272,7 @@ describe('OpenTelemetryTracer', () => { const span = otel.PubsubSpans.createPublisherSpan( tests.message, tests.topicInfo.topicName!, - 'tests' + 'tests', ); assert.ok(span); span.end(); @@ -298,11 +285,11 @@ describe('OpenTelemetryTracer', () => { assert.strictEqual(firstSpan.name, `${tests.topicInfo.topicId} create`); assert.strictEqual( firstSpan.attributes['messaging.destination.name'], - tests.topicInfo.topicId + tests.topicInfo.topicId, ); assert.strictEqual( firstSpan.attributes['messaging.system'], - 'gcp_pubsub' + 'gcp_pubsub', ); }); @@ -310,12 +297,12 @@ describe('OpenTelemetryTracer', () => { const span = otel.PubsubSpans.createPublisherSpan( tests.message, tests.topicInfo.topicName!, - 'tests' + 'tests', ); assert.ok(span); otel.PubsubSpans.updatePublisherTopicName( span, - 'projects/foo/topics/other' + 'projects/foo/topics/other', ); span.end(); @@ -328,7 +315,7 @@ describe('OpenTelemetryTracer', () => { assert.strictEqual( firstSpan.attributes['messaging.destination.name'], - 'other' + 'other', ); }); @@ -336,14 +323,14 @@ describe('OpenTelemetryTracer', () => { const parentSpan = otel.PubsubSpans.createPublisherSpan( tests.message, tests.topicInfo.topicName!, - 'tests' + 'tests', ); assert.ok(parentSpan); const span = otel.PubsubSpans.createReceiveSpan( tests.message, tests.subInfo.subName!, otel.spanContextToContext(parentSpan.spanContext()), - 'tests' + 'tests', ); assert.ok(span); span.end(); @@ -357,7 +344,7 @@ describe('OpenTelemetryTracer', () => { assert.strictEqual(childReadSpan.name, 'sub subscribe'); assert.strictEqual( childReadSpan.attributes['messaging.destination.name'], - 'sub' + 'sub', ); assert.strictEqual(childReadSpan.kind, SpanKind.CONSUMER); assert.ok(childReadSpan.parentSpanId); @@ -369,7 +356,7 @@ describe('OpenTelemetryTracer', () => { const span = otel.PubsubSpans.createPublisherSpan( message, topicName, - 'test' + 'test', ) as trace.Span; message.parentSpan = span; span.end(); @@ -377,7 +364,7 @@ describe('OpenTelemetryTracer', () => { const publishSpan = otel.PubsubSpans.createPublishRpcSpan( [message], topicName, - 'test' + 'test', ); publishSpan?.end(); @@ -388,7 +375,7 @@ describe('OpenTelemetryTracer', () => { assert.strictEqual( publishReadSpan.attributes['messaging.batch.message_count'], - 1 + 1, ); assert.strictEqual(publishReadSpan.links.length, 1); assert.strictEqual(childReadSpan.links.length, 1); diff --git a/test/test-utils.ts b/test/test-utils.ts new file mode 100644 index 000000000..c1eb6b4e6 --- /dev/null +++ b/test/test-utils.ts @@ -0,0 +1,53 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {SinonSandbox, SinonFakeTimers} from 'sinon'; + +type FakeTimersParam = Parameters[0]; +interface FakeTimerConfig { + now?: number; + toFake?: string[]; +} + +/** + * Utilities for unit test code. + * + * @private + */ +export class TestUtils { + /** + * This helper should be used to enable fake timers for Sinon sandbox. + * + * @param sandbox The sandbox + * @param now An optional date to set for "now" + * @returns The clock object from useFakeTimers() + */ + static useFakeTimers(sandbox: SinonSandbox, now?: number): SinonFakeTimers { + const config: FakeTimerConfig = { + toFake: [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'Date', + ], + }; + if (now) { + config.now = now; + } + + // The types are screwy in useFakeTimers(). I'm just going to pick one. + return sandbox.useFakeTimers(config as FakeTimersParam); + } +} diff --git a/test/topic.ts b/test/topic.ts index bdbb7c808..c918b21c6 100644 --- a/test/topic.ts +++ b/test/topic.ts @@ -34,7 +34,7 @@ const fakeUtil = Object.assign({}, util, { promisifySome( class_: Function, classProtos: object, - methods: string[] + methods: string[], ): void { if (class_.name === 'Topic') { promisified = true; @@ -196,7 +196,7 @@ describe('Topic', () => { it('should format name', () => { const formattedName = Topic.formatName_( PROJECT_ID, - TOPIC_UNFORMATTED_NAME + TOPIC_UNFORMATTED_NAME, ); assert.strictEqual(formattedName, TOPIC_NAME); }); @@ -229,7 +229,7 @@ describe('Topic', () => { PUBSUB.createSubscription = ( topic_: Topic, name: string, - options: CreateSubscriptionOptions + options: CreateSubscriptionOptions, ) => { assert.strictEqual(topic_, topic); assert.strictEqual(name, NAME); @@ -288,7 +288,7 @@ describe('Topic', () => { beforeEach(() => { topic.getMetadata = ( gaxOpts: CallOptions, - callback: RequestCallback + callback: RequestCallback, ) => { callback(null, fakeMetadata); }; @@ -301,7 +301,7 @@ describe('Topic', () => { assert.strictEqual(_topic, topic); assert.strictEqual(resp, fakeMetadata); done(); - } + }, ); }); @@ -324,7 +324,7 @@ describe('Topic', () => { topic.getMetadata = ( gaxOpts: CallOptions, - callback: GetTopicMetadataCallback + callback: GetTopicMetadataCallback, ) => { callback(error, apiResponse); }; @@ -335,7 +335,7 @@ describe('Topic', () => { assert.strictEqual(_topic, null); assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -345,7 +345,7 @@ describe('Topic', () => { topic.getMetadata = ( gaxOpts: CallOptions, - callback: GetTopicMetadataCallback + callback: GetTopicMetadataCallback, ) => { callback(error, apiResponse); }; @@ -356,7 +356,7 @@ describe('Topic', () => { assert.strictEqual(_topic, null); assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -370,7 +370,7 @@ describe('Topic', () => { topic.getMetadata = ( gaxOpts: CallOptions, - callback: GetTopicMetadataCallback + callback: GetTopicMetadataCallback, ) => { callback(error, apiResponse); }; @@ -455,7 +455,7 @@ describe('Topic', () => { topic.request = ( config: RequestConfig, - callback: GetTopicMetadataCallback + callback: GetTopicMetadataCallback, ) => { callback(error, apiResponse); }; @@ -472,7 +472,7 @@ describe('Topic', () => { topic.request = ( config: RequestConfig, - callback: GetTopicMetadataCallback + callback: GetTopicMetadataCallback, ) => { callback(null, apiResponse); }; @@ -509,14 +509,14 @@ describe('Topic', () => { { topic: topic.name, }, - options + options, ); const expectedGaxOpts = Object.assign( { autoPaginate: options.autoPaginate, }, - options.gaxOpts + options.gaxOpts, ); delete expectedOptions.gaxOpts; @@ -554,7 +554,7 @@ describe('Topic', () => { topic.request = ( config: RequestConfig, - callback: RequestCallback + callback: RequestCallback, ) => { callback(null, fakeSubs); }; @@ -590,7 +590,7 @@ describe('Topic', () => { assert.strictEqual(nextQuery, nextQuery_); assert.strictEqual(apiResponse, apiResponse_); done(); - } + }, ); }); }); @@ -746,7 +746,7 @@ describe('Topic', () => { topic.parent.subscription = ( name: string, - options: SubscriptionOptions + options: SubscriptionOptions, ) => { assert.strictEqual(name, subscriptionName); assert.deepStrictEqual(options, opts); @@ -759,7 +759,7 @@ describe('Topic', () => { it('should attach the topic instance to the options', done => { topic.parent.subscription = ( name: string, - options: SubscriptionOptions + options: SubscriptionOptions, ) => { assert.strictEqual(options.topic, topic); done(); diff --git a/tsconfig.json b/tsconfig.json index c78f1c884..51baa5572 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,8 +12,10 @@ "include": [ "src/*.ts", "src/**/*.ts", + "src/v1/*.json", "test/*.ts", "test/**/*.ts", - "system-test/*.ts" + "system-test/*.ts", + "protos/**/*.json" ] }